linux之sed

  • Post author:
  • Post category:linux


sample:

#在file文件的第二行后面添加一行hello和一行world

sed ‘2a hello\world’ file

#在第三行前面添加一行hello

sed ‘3i hello’ file

#删除第五行到最后一行

sed ‘5,$d’ file

#删除file文件的第二行并更新到file文件

sed -i ‘2d’ file

#替换file文件的第二行到第五行为一行hello和一行world

sed ‘2,5c hello\world’ file

#仅打印file文件中包含root的行

sed -n ‘/root/p’ file

#删除file中包含root的行 其他的行输出

sed ‘/root/d’ file

#将匹配root的行中shell替换为newshell并打印退出:print quit,加了q之后只打印替换成功的,没有加q,会打印匹配到root的所有行

sed -n ‘/root/{s/shell/newshell/;p;q;}’ /etc/passwd

#多点编辑:将file中第3行到最后一行删除,然后再将删除之后的行中root替换成newroot

sed -e ‘3,$d’ -e ‘s/root/newroot/’ file

#替换file中每一行中结尾的. 成 !

sed ‘s/\.$/\!/g’ file

#在file最后一行添加#end

sed ‘$a #end’ file

#找到匹配string的行 并删除该行后两行和匹配行

sed -i -e ‘/string/,+2d’ *

#找到匹配string的行 并删除该行的上一行

sed -i -e ‘$!N;/\n.*string/!P;D’ *

#找到匹配 插入或者更新商品扩展信息 的一行,并打印该行和后面两行

sed -n ‘/插入或者更新商品扩展信息/,+2p’ *Repo*

#在cisco后面一行添加CCIE


sed -i “/cisco/a\CCIE” 123.txt

&符号用来引用匹配上的字符

如:将所有单词两边加上[xxx]

echo this is en example | sed 's/\w+/[&]/g'
$>[this]  [is] [en] [example]



版权声明:本文为cs13970021734原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。