对于配置文件, 使用sed命令,不仅更加快捷,而且便于脚本中, 自动化操作
选项
-i 直接修改文件内容,而不是输出到终端 -n 取消默认的输出和 p 常搭配使用 -e 执行多条操作 内置命令字符 a 全拼 append d 全拼 delete i 全拼 insert p 全拼 print s 全拼substitute 替换
测试文件
cat >person.txt<<EOF andy bob cili haha kiki EOF
sed -f test.sed test.txt
sed -i.bak 's#bob#bobi#g' person.txt #修改并备份
查询元素
#输出第一行的内容 [root@localhost ~]# sed -n '1p' person.txt andy #查看cili 到kiki [root@localhost ~]# sed -n '/cili/,/kiki/p' person.txt cili haha kiki #查看第一行和第三行 [root@localhost ~]# sed -n '1p;3p' person.txt andy cili #查看cili 和kiki [root@localhost ~]# sed -n '/cili/p;/kiki/p' person.txt cili kiki #查看多个不连续的元素 [root@localhost ~]# sed -nr '/andy|cili|kiki/p' person.txt andy cili kiki
增加元素
#在尾行添加 [root@localhost ~]# sed '$aadu\nbule' person.txt andy bobi cili haha kiki adu bule #在第2行添加 [root@localhost ~]# sed '2ablue' person.txt andy bobi blue cili haha kiki #在andy后添加blue和hoho [root@localhost ~]# sed '/andy/abule\nhoho' person.txt andy bule hoho bobi cili haha kiki
删除元素
# 删除第一行 [root@localhost ~]# sed '1d' person.txt bobi cili haha kiki # 删除cili [root@localhost ~]# sed '/cili/d' person.txt andy bobi haha kiki # 删除1至3行 [root@localhost ~]# sed '1,3d' person.txt haha kiki # 删除1行和第3行 [root@localhost ~]# sed '1d;3d' person.txt bobi haha kiki # 删除andy [root@localhost ~]# sed '/andy/d' person.txt bobi cili haha kiki
替换元素
sed '2s/dog/cat/g' data.txt #如果没有/g 则只将每一行的第一个dog 替换成cat(行内全局) sed'2,3s/dog/cat/' data.txt [root@localhost~]# sed '2,$s/dog/cat/' data.txt dog cat cat cat cat # $表示到最后一行 [root@localhost~]# sed '/hellodog/s/dog/cat/' data.txt dog dog dog hellocat dog