awk基础-筛选IPv4地址

筛选IPv4地址

从ifconfig命令的结果中筛选出除了lo网卡外的所有IPv4地址。

ifconfig命令结果如下:

$ ifconfig
eth1      Link encap:Ethernet  HWaddr 00:50:56:c0:00:01
          inet addr:172.16.100.1  Bcast:172.16.100.255  Mask:255.255.255.0
          inet6 addr: fe80::1440:d790:2f3:4f7c/64 Scope:Unknown
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

eth2      Link encap:Ethernet  HWaddr 00:50:56:c0:00:08
          inet addr:192.168.200.1  Bcast:192.168.200.255  Mask:255.255.255.0
          inet6 addr: fe80::a885:c017:c36d:7244/64 Scope:Unknown
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Unknown
          UP LOOPBACK RUNNING  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

两种筛选ipv4地址方式:

## 1.法一:
ifconfig | awk '/inet / && !($2 ~ /^127/){print $2}'

# 按段落读取
## 2.法二:
ifconfig | awk 'BEGIN{RS=""}!/lo/{print $6}'

第一种是常规筛选方式。

第二种是按段落读取整个一段,每个网卡的信息属于一段,它保存在$0中,然后从这一段中取其中的ipv4地址字段$6