1. 程式人生 > >sed 命令使用(2)

sed 命令使用(2)

1、sed 命令的後項要引用取IP

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

[[email protected] 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,再輸出這行:

[[email protected] 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
[[email protected] scripts]#

3、sed 命令列印行

[[email protected] 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必須放到引數位的最後如果放到前面檔案會備份成這樣:

[[email protected] scripts]# sed -ir.2016.bak 's#^sed#s1#g' b.log #失敗的案例 
[[email protected] scripts]# ls
b.log       b.logr.2016.bak

[[email protected] scripts]# cat b.log.2018.bak
11

[email protected] scripts]# sed -i.2018.bak 's#11#sedcmd#g' b.log

[[email protected] scripts]# ls b.*
b.log  b.log.2018.bak

[[email protected] scripts]# cat b.log.2018.bak
11
[[email protected] scripts]# cat b.log
sedcmd