-e 或–expression=:表示用指定命令或者脚本来处理输入的文本文件。
-f 或–file=:表示用指定的脚本文件来处理输入的文本文件。
-h 或–help:显示帮助。
-n、–quiet 或 silent:表示仅显示处理后的结果。
-i:直接编辑文本文件。
a:增加,在当前行下面增加一行指定内容。
c:替换,将选定行替换为指定内容。
d:删除,删除选定的行。
i:插入,在选定行上面插入一行指定内容。
p:打印,如果同时指定行,表示打印指定行;如果不指定行,则表示打印所有内容;如果有非打印字符,则以 ASCII 码输出。其通常与“-n”选项一起使用。s:替换,替换指定字符。
y:字符转换。
[root@localhost conf]# sed -n ‘p’ abc.txt ;效果等同于cat
[root@localhost conf]# sed -n ‘3p’ abc.txt ##输出第 3 行
[root@localhost conf]# sed -n ‘3,5p’ abc.txt ##输出 3~5 行
[root@localhost conf]# sed -n ‘p;n’ cba.txt ##输出所有奇数行,n 表示读入下一行资料
[root@localhost conf]# sed -n ‘n;p’ cba.txt ##输出所有偶数行,n 表示读入下一行资料
[root@localhost conf]# sed -n ‘1,5{p;n}’ cba.txt ##输出第 1~5 行之间的奇数行(第 1、3、5 行)
{p;n}组合形式,最后一行如果轮到n,就需要执行下一个p
{p;n}相对于前面的范围输出
[root@localhost conf]# sed -n ‘10,${n;p}’ cba.txt ##输出第 10 行至文件尾之间的偶数行
读取的第 1 行是文件的第 10 行,读取的第 2行是文件的第 11 行,依此类推,所以输出的偶数行是文件的第 11 行、13 行直至文件结尾, 其中包括空行
[root@localhost conf]# sed -n ‘10,${p;n}’ cba.txt ##输出第 10 行至文件尾之间的奇数行
[root@localhost conf]# sed -n ‘2,$p’ cba.txt ##第2行开始输出到末尾
[root@localhost conf]# sed -n ‘/the/p’ httpd.conf ##输出包含the的行
[root@localhost conf]# sed -n ‘4,/the/p’ 123.txt ##输出第4行至第一个包含the的行
[root@localhost conf]# sed -n ‘/the/=’ 123.txt ##输出包含the 的行所在的行号,等号(=)用来输出行号
[root@localhost conf]# sed -n ‘/^the/p’ 123.txt ##输出以the开头的行
[root@localhost conf]# sed -n ‘/[0-9]$/p’ httpd.conf ##输出以数字结尾的行
[root@localhost conf]# sed -n ‘/
nl 命令用于计算文件的行数,结合该命令可以更加直观地查看到命令执行的结果
[root@localhost conf]# nl abc.txt | sed ‘3d’ ##删除第三行 删除了“tehisad”
删除的是缓存去的内容,源文件内容没有被删除
[root@promote conf]# nl cba.txt | sed ‘3,5d’ ##删除第 3~5 行
[root@localhost conf]# nl cba.txt | sed ‘/aa/d’ ##删除包含 aa的行,原本的第 11行被删除
[root@localhost conf]# nl cba.txt | sed ‘/aa/!d’ ##删除不包含 aa的行,用!符号表示取反操作
[root@localhost conf]# sed ‘/1/d’ cba.txt ##删除以小写字母开头的行
[root@localhost conf]# sed ‘/.$/d’ cba.txt ##删除以"."结尾的行
[root@localhost conf]# sed ‘/^$/d’ cba.txt ##删除所有空行
[root@localhost conf]# sed -e’/^KaTeX parse error: Expected group after '^' at position 6: /{n;/^̲/d}’ cba.txt ##删除重复的空行,只保留一个
执行命令后,只保留一个空行
在使用 sed 命令迁移符合条件的文本时,常用到以下参数
H:复制到剪贴板;
g、G:将剪贴板中的数据覆盖/追加至指定行;
w:保存为文件;
r:读取指定文件;
a:追加指定内容。
[root@localhost conf]# sed ‘/the/{H;d};$G’ cba.txt ##将包含the 的行迁移至文件末尾,{;}用于多个操作;
[root@localhost conf]# sed ‘3,5{H;d};14G’ cba.txt ##将第3-5行内容转移至第14行后不加d就不删除3-5行
[root@localhost conf]# sed ‘/the/w b.txt’ cba.txt ##将包含the 的行另存为文件b.txt
[root@localhost conf]# sed ‘/the/r /opt/55.txt’ cba.txt ##将文件/opt/55.txt 的内容添加到包含 the 的每行以后
[root@localhost conf]# sed ‘8aNew’ cba.txt ##第8行后插入一个新行,内容为New
[root@localhost conf]# sed ‘/the/aNew’ cba.txt ##在包含the 的每行后插入一个新行,内容为 New
[root@localhost conf]# sed ‘5aNew1\nNew2’ cba.txt ##在第5行后插入多行内容,中间的\n 表示换行
将1-5行的内容转移到10行后面
1.先创建一个脚本
2.[root@localhost conf]# sed -f opt.list cba.txt
a-z ↩︎