sed Streaming EDitor
语法: sed 【选项】 ‘【动作】’ 文件名
选项
-n 一般sed命令会把所有数据都输出到屏幕,如果加入此选项,则只会输出经过sed命令处理的行。
-e 允许对文件应用多条sed命令处理。
-i 将用sed命令处理的处理结果直接保存到原文件中,而不是在屏幕进行输出。
动作
a\ 追加,在当前行后追加一行或多行,追加多行时,在每一行后加入“\”表示追加内容未结束。
c\ 替换,将当前行替换为一行或者多行,替换为多行时,每一行结尾加“\”。
d 删除,删除指定的行。
p 打印,输出指定的行。
s 字符串替换,用一个字符串替换另一字符串,格式:“行范围s/旧字符串/新字符串/g”
cat -n Thanos.txt
1 I am zcn
2 you are the best
3 i have several small dreams.
4 you are the besti have several small dreams.
5 you are the best i have several small dreams.
6 you are the besti have several small dreams.
7 you are the best i have several small dreams.
8 I am learning bioinformatics.
9 you are the besti have several small dreams.
删除第2-7行和第9行
sed -ie '2,7d;9d' Thanos.txt
cat -n Thanos.txt
1 I am zcn
2 I am learning bioinformatics.
在第一行后面添加多行
sed -i '1a you are the best\ni have several small dreams.' Thanos.txt
cat -n Thanos.txt
1 I am zcn
2 you are the best
3 i have several small dreams.
4 I am learning bioinformatics.
Tips
1、在某行后面添加多行,记得在添加多行中的每一行中加入“\n”,不能只加“\”
2、运行两个删除命令 要加-e 动作并列要加;
替换命令
sed 's/i/you/g' Thanos.txt
I am zcn
you are the best
you have several small dreams.
you are the best
you have several small dreams.
I am learnyoung byouoyounformatyoucs.