1. 程式人生 > 其它 >【04-03】 利用sed 取出ifconfig命令中本機的IPv4地址

【04-03】 利用sed 取出ifconfig命令中本機的IPv4地址

【04-03】 利用sed 取出ifconfig命令中本機的IPv4地址

#檢視網絡卡資訊
[root@CentOS ~]# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0C:29:9F:C4:FD  
          inet addr:10.0.0.100  Bcast:10.0.0.255  Mask:255.255.255.0
          inet6 addr: fxxx::2xx:2xxx:xx9x:cxxx/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
RX packets:500 errors:0 dropped:0 overruns:0 frame:0 TX packets:182 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:47498 (46.3 KiB) TX bytes:18744 (18.3 KiB) lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::
1/128 Scope:Host UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 b) TX bytes:0 (0.0 b) #確定網絡卡名稱及篩選IP # -En E啟用正則n不自動列印 /inet 確定需要使用的行 /s@@@gp 全域性+輸出 (.*inet)刪除前面空格,第二個括號內全部內容,第三個括號為n後面的資料 [root@centos
-7 ~]# ifconfig eth0 | sed -En '/inet /s@(.*inet )(.*)( n.*)@\2@gp' 10.0.0.100 參考:方法 2s///p ;2s@@@p 對第二行進行過濾 -E使用正則 不使用則加反斜線轉義(\) # 第一種使用的是鎖定第二行,使用IP進行定位,刪除確定行前面及後面 [root@centos-7 ~]# ifconfig eth0 | sed -nr "2s/[^0-9]+([0-9.]+).*/\1/p" 10.0.0.100 [root@centos-7 ~]# ifconfig eth0 | sed -En '2s/^[^0-9]+([0-9.]{7,15}).*/\1/p' 10.0.0.100 [root@centos-7 ~]# ifconfig eth0 | sed -rn '2s/^[^0-9]+([0-9.]+) .*$/\1/p' 10.0.0.100 # 過濾第二行後刪除inet前面內容;第二個sed則過濾刪除包括netmask的內容 # 後面類似都是先刪除前面 保留中間 刪除後面的邏輯 [root@centos-7 ~]# ifconfig eth0 | sed -n '2s/^.*inet //p' | sed -n 's/netmask.*//p' 10.0.0.100 [root@centos-7 ~]# ifconfig eth0 | sed -n '2s/^.*inet //;s/ netmask.*//p' 10.0.0.100 [root@centos-7 ~]# ifconfig eth0 | sed -rn '2s/(.*inet )([0-9].*)(netmask.*)/\2/p' 10.0.0.100 觀察特徵,確定行數,掐頭去尾,取中間