经常会遇到在命令行取ip地址,或写脚本引用ip地址,需要使用命令取出来;下面的方法根据实际情况调整
下面的命令环境为centos6.6系统;
[[email protected] ~]# 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
[[email protected] ~]# ip add
1: lo: 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: 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方法:
[[email protected] ~]# ifconfig eth0|grep ‘inet addr:‘|cut -d: -f2|cut -d " " -f1
192.168.20.50
sed方法:使用正则进行替换
[[email protected] ~]# ifconfig eth0|sed -nr ‘2s#^.*addr:(.*) Bca.*$#\1#g‘p
192.168.20.50
sed方法(不太好理解)
匹配/inet /这一行 进行2次替换,替换为空,剩下的就是ip地址;
[[email protected] ~]# ifconfig eth0|sed -n ‘/inet /{s/.*addr://;s/ .*//;p}‘
192.168.20.50
awk方法:
[[email protected] ~]# ifconfig eth0|awk ‘/inet addr:/ {print $2}‘|awk -F: ‘{print $2}‘
192.168.20.50
awk 一条命令方法:(根据实际环境,查看ip所在行进行调整)
[[email protected] ~]# ip add|awk -F ‘[ /]+‘ ‘NR==8 {print $3}‘
192.168.20.50
时间: 12-08