awk命令统计ifconfig输出网卡与Ip地址

发布时间:2020-10-20编辑:脚本学堂
awk命令的例子,awk统计ifconfig命令输出的网络配置信息中的网卡接口与ip地址,awk命令与sub函数的用法。

linux系统中,用ifconfig命令查看网络配置信息(ifconfig命令实例教程

复制代码 代码示例:
[root@mail log]# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0F:1F:6E:65:25
          inet addr:172.16.2.12  Bcast:172.16.2.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:60609641 errors:0 dropped:0 overruns:0 frame:0
          TX packets:63241643 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1877695464 (1790.7 Mb)  TX bytes:2810452038 (2680.2 Mb)
          Interrupt:16
eth0:0    Link encap:Ethernet  HWaddr 00:0F:1F:6E:65:25
          inet addr:172.16.2.13  Bcast:172.16.2.255  Mask:255.255.255.0
          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 txqueuelen:1000
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)
          Interrupt:16
eth0:1    Link encap:Ethernet  HWaddr 00:0F:1F:6E:65:25
          inet addr:172.16.2.14  Bcast:172.16.255.255  Mask:255.255.255.0
          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 txqueuelen:1000
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)
          Interrupt:16

打印结果:
eth0    172.16.2.12
eth0:0  172.16.2.13
eth0:1  172.16.2.14
 
例子:
 

复制代码 代码示例:
[root@mail log]#  ifconfig | awk '/eth/{inter=$1;getline;sub(/inet addr:/,"");print inter,$1}'
eth0 172.16.2.12
eth0:0 172.16.2.13
eth0:1 172.16.2.14
 

其中有getline读取下一行,sub函数。
 
例子:
 

复制代码 代码示例:
[root@mail log]#  ifconfig | awk '/eth/{inter=$1;getline;split($2,x,":");print inter,x[2]}'
eth0 172.16.2.12
eth0:0 172.16.2.13
eth0:1 172.16.2.14
 

以上命令中使用了split函数,把$2字段addr:172.16.2.13用split用于:分界符,存储在两个数组中。