sed:用于过滤和转换文件的流编辑器
执行方式: sed [options] 'command' [filename]
sed [options] '/pattern/ command'
sed [options] 'n,m command' (n,m为行号)
command(命令):
s/re/string/ : 替换 使用字符串string替换正则表达式re的内容 (只替换第一个)
#echo hello gino hello wrold | sed 's/\<hello\>/Hello/'
Hello gino hello wrold
g :行内全部替换
# echo hello gino hello wrold | sed 's/\<hello\>/Hello/g'
Hello gino Hello wrold
匹配样式的行进行替换示例 :# cat sample_one
one 1
two 1
three 1
one 1
two 1
two 1
three 1
# sed '/two/ s/1/2/' sample_one
one 1
two 2
three 1
one 1
two 2
two 2
three 1
d : 删除行
# sed '/two/ d' sample_one
one 1
three 1
one 1
three 1
# sed '/two/ !d' sample_one #删除匹配以外的行
two 1
two 1
two 1
# sed '1,5 d' sample_one #删除第1到第5行
two 1
three 1
i\ :插入文本(行前)
# sed '5 i\hello gino' sample_one
one 1
two 1
three 1
one 1
hello gino
two 1
two 1
three 1
a\ :追加文本(行后)
# sed '5 a\hello gino' sample_one
one 1
two 1
three 1
one 1
two 1
hello gino
two 1
three 1
c\ : 替换文本(本行)
# sed '5 c\hello gino' sample_one
one 1
two 1
three 1
one 1
hello gino
two 1
three 1
p : 打印
# sed '5 p' sample_one one 1
two 1
three 1
one 1
two 1
two 1
two 1 #打印出来的一行
three 1
w : 写入到文件结尾
# sed -e '/two/ s/1/2/' -e '/three/ s/1/3/' -e '1,3 w sample_two' sample_one
one 1
two 2
three 3
one 1
two 2
two 2
three 3
# cat sample_two
one 1
two 2
three 3
q : 提前退出
# sed '3q' sample_one #处理到第三行就退出sed命令
one 1
two 1
three 1
options(选项):
-f : 从文件中读取替换规则
# cat replace_list /two/ s/1/2/
/three/ s/1/3/
# sed -f replace_list sample_one
one 1
two 2
three 3
one 1
two 2
two 2
three 3
-n : 禁止显示
# sed -n '/two/ d' sample_one #不显示结果
-i :对文件进行操作(不加此选项 不改变文件的内容,只改变显示的结果而已)
# cat sample_one
two 1
#sed -i 'p' sample_one
# cat sample_one #源文件被改变了
two 1
two 1
-e : 执行多个sed
# sed -e '/two/ s/1/2/' -e '/three/ s/1/3/' sample_one
one 1
two 2
three 3
one 1
two 2
two 2
three 3
ubuntu还支持另外一种 执行多个sed 的语法(其他linux系统没尝试)
# sed '/two/ s/1/2/;/three/ s/1/3/' sample_one
one 1
two 2
three 3
one 1
two 2
two 2
three 3