在linux下如何用正则表达式执行ifconfig命令,只提取IP地址!

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在linux下如何用正则表达式执行ifconfig命令,只提取IP地址!相关的知识,希望对你有一定的参考价值。

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

1、

 [[email protected] ~]# ifconfig eth0|grep ‘inet addr:‘    ###过滤不是IP地址的行

    inet addr:192.168.16.100  Bcast:192.168.16.255  Mask:255.255.255.0

    或者

 [[email protected] ~]# ifconfig eth0|sed -n ‘2p‘    ###过滤不是IP地址的行

    inet addr:192.168.16.100  Bcast:192.168.16.255  Mask:255.255.255.0

 

[[email protected] ~]# 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地址头部了。


 [[email protected] ~]# 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地址!的主要内容,如果未能解决你的问题,请参考以下文章

c语言下如何用正则或者字符串查找匹配特定字符串并提取出来

linux下如何用php读取word

linux下如何用C代码执行一个cmd命令,然后可以控制该命令的结束

linux下如何用c语言调用shell命令

unix下如何用ps命令得到进程的路径

linux下如何用c语言调用shell命令