我只想要Linux的IP地址

大家都知道ifconfig 可以查看centos的ip地址,但是我如果只要ip地址該怎麼辦呢?
首先上ifconfig

[root@centos ~]# ifconfig eth0 
eth0      Link encap:Ethernet  HWaddr 00:50:56:94:7D:88  
          inet addr:10.10.9.110  Bcast:10.10.9.255  Mask:255.255.255.0
          inet6 addr: fe80::250:56ff:fe94:7d88/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:633616 errors:0 dropped:0 overruns:0 frame:0
          TX packets:341279 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:970671417 (925.7 MiB)  TX bytes:43671671 (41.6 MiB)

我現在想把ip地址所在的第2行取出來:

[root@centos ~]# ifconfig eth0 | awk 'NR==2'
          inet addr:10.10.9.110  Bcast:10.10.9.255  Mask:255.255.255.0

或者通過grep來取也可以

[root@centos ~]# ifconfig eth0 | grep Mask
          inet addr:10.10.9.110  Bcast:10.10.9.255  Mask:255.255.255.0

在此基礎之上,把ip地址取出來

[root@centos ~]# ifconfig eth0 | awk 'NR==2 {print $2}' 
addr:10.10.9.110  //此時還需要一個管道把前面的addr:去掉即可

[root@centos ~]# ifconfig eth0 | awk 'NR==2 {print $2}' | awk -F ":" '{print $2}'
10.10.9.110

換一種思路,用cut命令

cut 截取命令,-d " " 用引號內符號分割,-f n n代表分割之後的區域

[root@centos ~]# ifconfig eth0 | grep Mask | cut -d ":" -f2 | cut -d " " -f1
10.10.9.110

第三種方法,awk的高級用法

awk命令通過-F "[ : ]+" 可以使用多個分隔符分割文本

[root@centos ~]#  ifconfig | grep "Bcast" | awk -F "[: ]+" '{print $4}'
10.10.9.110

第四種方法,我可以在ifcfg-eth0配置文件上動腦筋

[root@centos ~]# grep IPADDR /etc/sysconfig/network-scripts/ifcfg-eth0 | cut -d "=" -f2
10.10.9.110

第五種方法,可以叫做野路子,獲取到的是外網ip

[root@centos ~]# curl ifconfig.me

第六種方法,只用sed

[root@centos ~]# ifconfig eth0 | sed -n '/inet addr/p' | sed 's#^.*addr:##g' | sed 's# Bc.*$##g'
10.10.9.110 

第七種方法 我還運用的不熟練

sed的反向匹配

[root@centos ~]# ifconfig eth0 | sed -n 's#^.*addr:\(.*\) Bcas.*$#\1#gp'
10.10.9.110 

說了這麼多,發現linux命令博達而精深,只有膜拜的份了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章