1. 程式人生 > >在linux下如何用正則表達式執行ifconfig命令,只提取IP地址!

在linux下如何用正則表達式執行ifconfig命令,只提取IP地址!

linux 如何 正則

方法太多,先簡單到簡捷循序漸進。

1、

[root@centos6 ~]# ifconfig eth0|grep ‘inet addr:‘ ###過濾不是IP地址的行

inet addr:192.168.16.100 Bcast:192.168.16.255 Mask:255.255.255.0

或者

[root@centos6 ~]# ifconfig eth0|sed -n ‘2p‘ ###過濾不是IP地址的行

inet addr:192.168.16.100 Bcast:192.168.16.255 Mask:255.255.255.0

[root@centos6 ~]# ifconfig eth0|sed -n ‘2p‘|sed -n ‘s#^.*dr:##gp‘

192.168.16.100 Bcast:192.168.16.255 Mask:255.255.255.0 ###已經去掉IP地址頭部了。


[root@centos6 ~]# ifconfig eth0|sed -n ‘2p‘|sed -n ‘s#^.*dr:##gp‘|sed -n ‘s#B.*$##gp‘
###去掉IP地址尾巴。

192.168.16.100


2、 用grep或sed &&cut 組合提取


ifconfig eth0|grep "inet addr:"|cut -d":" -f2|cut -d" " -f1

ifconfig eth0|grep "inet addr:"|cut -f2 -d":"|cut -f1 -d" "

ifconfig eth0|grep "inet addr:"|cut -d: -f2|cut -d" " -f1

ifconfig eth0|sed -n ‘2p‘|cut -c21-35

3、 用grep或sed &&awk 來提取


ifconfig eth0|grep "inet addr"|awk -F‘[ :]+‘ ‘{print $4}‘

ifconfig eth0|sed -n ‘/inet addr/p‘|awk -F‘[: ]+‘ ‘{print $4}‘

4、 直接用sed正則表達式來匹配

ifconfig eth0|sed -rn ‘s#^.*dr:(.*)B.*$#\1#gp‘

ifconfig eth0|sed -n ‘s#^.*dr:\(.*\)B.*$#\1#gp‘


5、 直接用awk正則表達式來匹配


ifconfig eth0|awk -F ‘[ :]+‘ ‘NR==2 {print $4}‘

ifconfig eth0|awk -F ‘[: ]+‘ ‘/Bcast/ { print $4}‘

ifconfig eth0|awk -F ‘[: ]+‘ ‘/inet addr:/ { print $4}‘

ifconfig eth0|awk -F ‘[ :]+‘ ‘$0 ~ "inet addr"{print $4}‘

6、 直接用grep正則表達式來匹配IP地址數字


ifconfig eth0|grep -o ‘\([1-9]\{1,3\}\.\)\{3\}[0-4]\{3,\}‘

#####[0-4]不要大於4否則子網掩碼也會提取出來。

7、

ip addr|grep -Po ‘[^ ]+(?=/\d)‘|sed -n ‘3p‘

8、 直接提取IP地址文件。

/etc/sysconfig/network-scripts/ifcfg-eth0

cat /etc/sysconfig/network-scripts/ifcfg-eth0|sed -n ‘10p‘|cut -d"=" -f2

在linux下如何用正則表達式執行ifconfig命令,只提取IP地址!