sed也成stream editor,流编辑器,是Linux上常用的文本处理工具。
通用格式:sed 行范围 模式/RegExp/ 文件
模式:
d 删除
p 打印符合条件的行
a \string 追加显示(后行)
i \string 追加显示(前行)
r 在某行后插入另一个文本
w 保存到另一个文件
s/pattern/string/ 查找并替换(只替换每行第一个)
s/pattern/string/g 全局替换
1、将test.txt第三行替换为hello输出:
#!/bin/bash
sed "3c hello" test.txt
2、将test.txt第三行替换为hello,并存入原文件:
#!/bin/bash
sed -i "3c hello" test.txt
3、删除test.txt的第一行到第三行:
sed '1,3d' test.txt
4、删除test.txt的第四行到最后一行:
sed '4, $d' test.txt
5、删除包含hello的行:
sed '/hello/d' test.txt
6、删除第5行后的两行:
sed '5, +2d' test.txt
7、hello开头的行后追加一行world
sed '/^hello/a world' test.txt
8、把含有abc的行写入b.txt文件:
sed '/abc/w b.txt' test.txt
9、把/etc/fstab中#开头的行换成#*#
sed 's/^#/#*#/' /etc/fstab