[root@oldboylinux ~]#ifconfig eth1
eth1 Link encap:Ethernet HWaddr 08:00:27:E7:F4:74
inet addr:192.168.0.109 Bcast:192.168.0.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:fee7:f474/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:56435 errors:0 dropped:0 overruns:0 frame:0
TX packets:23873 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:26220558 (25.0 MiB) TX bytes:5091087 (4.8 MiB)
取出192.168.0.109
思路:
- 取出第二行
- 在第二行中截取,或者进行分割
方法1
原理:通过grep 过滤取出目标行,然后按照cut的字符进行截取
[root@oldboylinux ~]#ifconfig eth1 | grep -w inet | cut -c 21-34
192.168.0.109
[root@oldboylinux ~]#ifconfig eth1 | grep -E "^*inet add" | cut -c 21-34
192.168.0.109
[root@oldboylinux ~]#ifconfig eth1 | grep "inet add" | cut -c 21-34
192.168.0.109
[root@oldboylinux ~]#
方法2:
原理:
- 过滤出目标行
- awk 用:进行分割
- awk 用" "空格进行分割
[root@oldboylinux ~]#ifconfig eth1 | grep "inet add" | awk -F ":" '{print $2}'
192.168.0.109 Bcast
[root@oldboylinux ~]#ifconfig eth1 | grep "inet add" | awk -F ":" '{print $2}' | awk -F " " '{print $1}'
192.168.0.109
[root@oldboylinux ~]#
方法3
原理:
- 过滤出目标行
- 用awk将:和空格" "进行分割
[root@oldboylinux ~]#ifconfig eth1 | grep "inet add" | awk -F "[ :]" '{print $13}'
192.168.0.109
方法4
原理
- 过滤出目标行
- 用awk 后面+多个分割符为1个
[root@oldboylinux ~]#ifconfig eth1 | grep "inet add" | awk -F "[ :]+" '{print $4}'
192.168.0.109
方法4
原理:
NR过滤出来行号
[root@oldboylinux ~]#ifconfig eth1 | awk -F "[ :]+" 'NR==2{print $4}'
192.168.0.109