正则表达式(三剑客之sed)

1.sed工具的使用

1.1 sed工具

1)命令格式:sed -n n p filename

1.2 打印某行

1)打印第二行

[root@localhost ~]# sed -n '2'p /etc/passwd

2)第二行重复打印

[root@localhost ~]# sed '2'p /etc/passwd

3)所有行全部打印

[root@localhost ~]# sed -n '1,$'p /etc/passwd

4)指定某个区间打印

[root@localhost ~]# sed -n '1,3'p /etc/passwd

1.3 打印包含某个字符串的行

1)打印包含root的行

[root@localhost ~]# sed -n '/root/'p /etc/passwd

2)打印以ro开头的行

[root@localhost ~]# sed -n '/^ro/'p /etc/passwd

3)打印以in结尾的行

[root@localhost ~]# sed -n '/in$/'p /etc/passwd

4)打印单个字符的行

[root@localhost ~]# sed -n '/r..o/'p /etc/passwd

5)打印匹配ooo零次或者多次的行

[root@localhost ~]# sed -n '/ooo*/'p /etc/passwd

6)sed命令加-e可以实现多个行为

[root@localhost ~]# sed -n -e '/r..o/'p -e '/ooo*/'p /etc/passwd

1.4 删除某些行

[root@localhost ~]# sed '1'd /etc/passwd

[root@localhost ~]# sed '1,4'd /etc/passwd

1.5 替换字符或者字符串

1)参数s表示替换的动作,参数g表示本行全局替换,如果不加g则只替换本行出现的第一个

sed -n '/r.o/'p /etc/passwd |sed -n '1,2s/ot/to/g'p

[root@localhost ~]# sed -n '/r.o/'p /etc/passwd |sed -n '1,2s/ot/to/'p

2)除了可以使用/作为分隔符外,我们还可以使用其他特殊字符

[root@localhost ~]# sed -n -e '/r.o/'p -e 's#ot#to#g'p /etc/passwd

[root@localhost ~]# sed -n -e '/r.o/'p -e 's@ot@to@g'p /etc/passwd

3)如何删除文档中的所有的数字或者字母呢

[root@localhost ~]# sed 's/[0-9]//g' /etc/passwd

[root@localhost ~]# sed 's/[a-z,A-Z]//g' /etc/passwd

1.6 调换两个字符串的位置

1)

[root@localhost ~]# sed 's/\(rot\)\(.*\)\(bash\)/\3\2\1/' /etc/passwd

2)上例中用()把想要的替换的字符打包成了一个整体,转义符\看起来很乱,加上-r就可以省略它

[root@localhost ~]# sed -r 's/(rot)(.*)(bash)/\3\2\1/' /etc/passwd

3)除了调换两个字符串的位置。还可以用sed在某一行前后增加指定内容

[root@localhost ~]# sed 's/^.*$/123&/' /etc/passwd

1.7 直接修改文件的内容

[root@localhost ~]# sed -i 's/ot/to/g' /etc/passwd

[root@localhost ~]# sed -i 's/to/ot/g' /etc/passwd

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值