方法太多,先简单到简捷循序渐进。

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 组合提取

[root@centos6 ~]#  ifconfig eth0|grep "inet addr:"|cut -d":" -f2|cut -d" " -f1

[root@centos6 ~]#  ifconfig eth0|grep "inet addr:"|cut -f2 -d":"|cut -f1 -d" "

[root@centos6 ~]#  ifconfig eth0|grep "inet addr:"|cut -d: -f2|cut -d" " -f1

[root@centos6 ~]#  ifconfig eth0|sed -n '2p'|cut -c21-35

    cut 截取命令,-d " " 用引号内符号分割,-f n n代表分割之后的区域


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


[root@centos6 ~]#  ifconfig eth0|grep "inet addr"|awk -F'[ :]+' '{print $4}'

[root@centos6 ~]#  ifconfig eth0|sed -n '/inet addr/p'|awk -F'[: ]+' '{print $4}'


4、    直接用sed正则表达式来匹配  

 

[root@centos6 ~]# ifconfig eth0|sed -rn 's#^.*dr:(.*)B.*$#\1#gp'

[root@centos6 ~]# ifconfig eth0|sed  -n 's#^.*dr:\(.*\)B.*$#\1#gp'


5、    直接用awk正则表达式来匹配


[root@centos6 ~]# ifconfig eth0|awk -F '[ :]+'  'NR==2 {print $4}'

[root@centos6 ~]# ifconfig eth0|awk -F '[: ]+'  '/Bcast/ { print $4}'

[root@centos6 ~]# ifconfig eth0|awk -F '[: ]+'  '/inet addr:/ { print $4}'

[root@centos6 ~]# ifconfig eth0|awk -F '[ :]+'  '$0 ~ "inet addr"{print $4}'


6、    直接用grep正则表达式来匹配IP地址数字

[root@centos6]#  ifconfig eth0|grep -o "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-4 6-9]\{3\}"

 或者下面精简的方法:

[root@centos7]# ifconfig eth0|grep -Eo '([0-9]+[.]){3}[0-9]+'|grep -v "255"

10.0.0.61


 ifconfig eth0|grep -Po '(?<=inet )[0-9.]+'        #centos 7# (centos 7)

10.0.0.31

ifconfig eth0|grep -Po '(?<=addr:)[0-9.]+'    # (centos 6)

ifconfig eth0|egrep -o "([0-9]{1,3}\.){3}[0-9]{1,3}"|grep -wv 255

#第一次优化后

ifconfig eth0|grep -Eo '([0-9]+\.){3}([0-9]+)'|grep -wv "255"


#第二次优化后

ifconfig eth0|grep -Po '[0-9.]+(?=  netmask)'     #centos 7(两个空格)

ifconfig eth0|grep -Po '(?<=inet )[0-9.]+'     #centos 7

ifconfig eth0|grep -Po '[0-9.]+(?=  Bcast)'   #centos 6 (两个空格)


ifconfig eth0|grep -Po '(\d{1,3}\W){3}\d{1,3}'|grep -v "255"

#第三次优化后

ifconfig eth0|grep -Po "[\d.]+(?=  netmask)"  #centos 7(两个空格)

ifconfig eth0|grep -Po "[\d.]+(?=  Bcast)"    #centos 6 (两个空格)


7、

[root@centos6 ~]# ip addr|grep -Po '[^ ]+(?=/\d)'|sed -n '3p'


[root@centos6 ~]# ifconfig eth0|sed -n '2p'|grep -Pio '[^ :a-z]+'|sed -n 1p


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

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

[root@centos6 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0|sed -n '10p'|cut -d"=" -f2


9、     hostname -I| awk '{print $1}'


10、    获取的是公网IP


11、

    ip route |awk 'NR==1{print $NF}'

    ip route |awk 'NR<2{print $NF}'