经常会遇到在命令行取ip地址,或写脚本引用ip地址,需要使用命令取出来;下面的方法根据实际情况调整
下面的命令环境为centos6.6系统;
[root@localhost ~]# ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:0C:29:2A:03:61
inet addr:192.168.20.50 Bcast:192.168.20.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe2a:361/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:339 errors:0 dropped:0 overruns:0 frame:0
TX packets:270 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:30384 (29.6 KiB) TX bytes:30677 (29.9 KiB)
Interrupt:18 Base address:0x2000
[root@localhost ~]# ip add
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 1000
link/ether 00:0c:29:2a:03:61 brd ff:ff:ff:ff:ff:ff
inet 192.168.20.50/24 brd 192.168.20.255 scope global eth0
inet6 fe80::20c:29ff:fe2a:361/64 scope link
valid_lft forever preferred_lft forever
grep+cut方法:
[root@localhost ~]# ifconfig eth0|grep 'inet addr:'|cut -d: -f2|cut -d " " -f1
192.168.20.50
sed方法:使用正则进行替换
[root@localhost ~]# ifconfig eth0|sed -nr '2s#^.*addr:(.*) Bca.*$#\1#g'p
192.168.20.50
sed方法(不太好理解)
匹配/inet /这一行 进行2次替换,替换为空,剩下的就是ip地址;
[root@localhost ~]# ifconfig eth0|sed -n '/inet /{s/.*addr://;s/ .*//;p}'
192.168.20.50
awk方法:
[root@localhost ~]# ifconfig eth0|awk '/inet addr:/ {print $2}'|awk -F: '{print $2}'
192.168.20.50
awk 一条命令方法:(根据实际环境,查看ip所在行进行调整)
[root@localhost ~]# ip add|awk -F '[ /]+' 'NR==8 {print $3}'
192.168.20.50
本文出自 “模范生的学习博客” 博客,请务必保留此出处http://mofansheng.blog.51cto.com/8792265/1721127