sed 命令使用(2)

1、sed 命令的后项要引用取IP

[root@localhost scripts]# ifconfig enp0s3|grep 'inet '|sed -r 's#.*inet (.*) netmask.*$#\1#g'
192.168.0.3
[root@localhost scripts]#

[root@localhost scripts]# ifconfig enp0s3
enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.3  netmask 255.255.255.0  broadcast 192.168.0.255

  .*inet                (.*)    \1                netmask.*$

    sed -r 's#.*inet (.*) netmask.*$#\1#g;上述颜色相同的代表内容统一;(.*)括号的内容就是选定的内容用 \1表示;若有两个从左向右的方向排序\1 \2……

-r 支持正则表达式

2、sed 查找内容并执行命令

查找/etc/passwd,找到root对应的行,执行后面花括号中的一组命令,每个命令之间用分号分隔,这里把bash替换为blueshell,再输出这行:

[root@localhost scripts]# sed -n '/root/{s/bash/blueshell/;p}' /etc/passwd
root:x:0:0:root:/root:/bin/blueshell
operator:x:11:0:operator:/root:/sbin/nologin
[root@localhost scripts]#

3、sed 命令打印行

[root@localhost scripts]# sed   "=" color.sh
1
#!/bin/sh
2
RED_COLOR='\E[1;31m'
3
GREEN_COLOR='\E[1;32m'
4
YELLOW_COLOR='\E[1;33m'
5

4、sed 修改文件加备份加

-i:后跟备份成的文件名;注意:如果sed 跟多个参数进行文件备份 -i必须放到参数位的最后如果放到前面文件会备份成这样:

[root@localhost scripts]# sed -ir.2016.bak 's#^sed#s1#g' b.log #失败的案例 
[root@localhost scripts]# ls
b.log       b.logr.2016.bak

[root@localhost scripts]# cat b.log.2018.bak
11

root@localhost scripts]# sed -i.2018.bak 's#11#sedcmd#g' b.log

[root@localhost scripts]# ls b.*
b.log  b.log.2018.bak

[root@localhost scripts]# cat b.log.2018.bak
11
[root@localhost scripts]# cat b.log
sedcmd

猜你喜欢

转载自blog.csdn.net/LINU_BW/article/details/84843767
今日推荐