sed 使用介绍

第6周第4次课(4月26日)

课程内容:

9.4/9.5 sed

 

9.4/9.5 sed

操作实例如下

sed和grep比较起来,sed也可以实现grep的功能,但是没有颜色显示,sed强项是替换一些指定的字符。

sed  实现匹配的功能

[root@jimmylinux-002 sed]# sed '/root/'p test.txt  把文件所有内容都打印出来

[root@jimmylinux-002 sed]# sed -n '/root/'p test.txt 

这样就可以只匹配关键词内容,其他无关的不打印出来。

同样也支持.、*、+、花括号这样的选项

打印指定的行

sed -e    不仅要把指定的第几行打印出来,还要匹配满足的字符串。

sed -e匹配一次,后面的root有符合一次,所以打印出来2行一样的内容。 

[root@jimmylinux-002 sed]# sed -n '/bus/'Ip test.txt  

加大写I也可以不区分大小写,会把带bus无论大小写的都打印出来。

使用d选项可以删除指定的行

[root@jimmylinux-002 sed]# sed -i '/user2/'d test.txt  把user2相关的行删除

[root@jimmylinux-002 sed]# sed '1,10s/root/toor/g' test.txt  s表示替换,g表示全局,把root替换成toor。

[root@jimmylinux-002 sed]# sed -r '1,10s/ro+/r/g' test.txt  支持正则表达式去查找替换

[root@jimmylinux-002 sed]# head test.txt |sed -r 's/([^:]+):(.*):([^:]+)/\3:2:\1/'  

把第一段和最后一段交换,就是root和bin/bash、bin和sbin/nologin 顺序前后交换。

[root@jimmylinux-002 sed]# head test.txt |sed 's/[a-zA-Z]//g'  

把文档里面所有的英文字母全部删除掉,最后就只剩数字和一些特殊符号了。

[root@jimmylinux-002 sed]# head test.txt |sed -r 's/(.*)/aaa:&/'

在所有行前面加上一个固定的字符串

 

posted @ 2018-04-25 21:50  吉米乐享驿站  阅读(445)  评论(0编辑  收藏  举报