sed命令

回复 收藏
sed命令
[root@awulinux ~]# sed -n '10'p 2.txt     这里的p表示打印的意思,加上-n后就可以打印符合规则的行,如果不加会把2.txt从头到尾打印一遍

[root@awulinux ~]# sed -n '1,10'p 2.txt     打印1到10行

[root@awulinux ~]# sed -n '5,$'p 2.txt      打印5到末行
[root@awulinux ~]# wc -l 2.txt              查看2.txt共有多少行
29 2.txt

[root@awulinux ~]# sed -n '/root/'p 2.txt     打印包含某个字符串的行

[root@awulinux ~]# sed -n '/r.o/'p 2.txt     .表示任意一个字符

[root@awulinux ~]# sed -n '/r*o/'p 2.txt     *表示零个或多个*前面的字符   

[root@awulinux ~]# sed -n '/r.*o/'p 2.txt    .*表示任意个任意字符

[root@awulinux ~]# sed -n '/r\?o/'p 2.txt     ?表示0个或1个?前面的字符,但是这里需要用脱依符'\'

[root@awulinux ~]# sed -n '/r\+o/'p 2.txt    +表示1个或多个+前面的字符

[root@awulinux ~]# sed -n 'root\|nologin/'p 2.txt     |表示或者

[root@awulinux ~]# sed -n '/\(oo\)\+/'p 2.txt     表示1对或者多对oo
[root@awulinux ~]# sed -n '/\(rr\)\+/'p 2.txt       表示1对或者多对rr

[root@awulinux ~]# sed -r -n '/(rr)+/'p 2.txt        表示1对或者多对rr,这里加上-r后,不需要脱义了
[root@awulinux ~]# sed -r -n 'root|nologin/'p 2.txt   

[root@awulinux ~]# sed -n -r '/[0-9]/'p 2.txt           打印含有数字的行
[root@awulinux ~]# sed -n -r '/[^0-9]/'p 2.txt         打印不含有非数字行,既不含有数字的行
[root@awulinux ~]# sed -n -r '/[^a-zA-Z]/'p 2.txt    打印不含有字母的行

[root@awulinux ~]# sed -n -r '/^$/'p 2.txt    ^$表示空行

[root@awulinux ~]# sed '/^$/'d 2.txt      删除空行

[root@awulinux ~]# sed '/[0-9]/'d 2.txt      删除含数字的行
[root@awulinux ~]# sed '/[a-zA-Z]/'d 2.txt   删除含有字母的行

[root@awulinux ~]# sed '1,19'd 2.txt      删除第1到19行

[root@awulinux ~]# sed -i '1,19'd 2.txt     -i 会对文件内容进行操作

sed 替换功能

[root@awulinux ~]# sed '1,10s/nologin/login/g' 2.txt     将1到10行的nologin替换为login
[root@awulinux ~]# sed '1,2s/ot/to/g' 2.txt
说明:s就是替换的意思,g表示全局替换,否则只替换一次。这里的/也可以换为#、@等

[root@awulinux ~]# sed 's/nologin/login/g' 2.txt         全局替换

[root@awulinux ~]# sed 's#^.*$#login#g' 2.txt   ^.*$表示整行

[root@awulinux ~]# sed 's#^.*$#&login#g' 2.txt     将所有行后面加上login
[root@awulinux ~]# sed 's#^.*$#& login#g' 2.txt    将所有行后面加上 login

[root@awulinux ~]# sed 's#[0-9]##g' 2.txt     删除所有的数字,其实就是把所有数字替换为空字符
[root@awulinux ~]# sed 's/[0-9]//g' 2.txt

[root@awulinux ~]# sed 's#[a-zA-Z]##g' 2.txt    删除所有的字母
[root@awulinux ~]# sed 's/[a-zA-Z]//g' 2.txt

[root@awulinux ~]# sed 's#[^0-9a-zA-Z]##g' 2.txt    删除除了字母,数字以外的,既特殊符号。剩余字母数字,空行

[root@awulinux ~]# sed -r 's#(^[a-z]+)(:.*:)(.*$)#\3\2\1#g' 2.txt       把第一段以字母开头的和最后一段调换位置   .*$表示最后一段
[root@awulinux ~]# sed -r 's#(^[a-z0-9]+)(:.*:)(.*$)#\3\2\1#g' 2.txt    把第一段以字母和数字开头的和最后一段调换位置

[root@awulinux ~]# sed -n '/user/p; /awu/p' 2.txt    用;实现多个语句匹配  打印出包含user和awu的行

[root@awulinux ~]# sed -n -r '/user|awu/p' 2.txt     |表示或者

[root@awulinux ~]# sed -n -e '/user/p' -e '/awu/p' 2.txt    -e可实现同时进行多个任务   相当于sed -n '/user/p; /awu/p' 2.txt
2016-06-16 23:31 举报
已邀请:
0

善思致用

赞同来自:

有一些不够严谨

回复帖子,请先登录注册

退出全屏模式 全屏模式 回复
评分
可选评分理由: