使用awk过滤出来eth0的IP

原始输出

[root]# ifconfig
eth0      Link encap:Ethernet  HWaddr 6C:92:BF:2B:DC:2F  
          inet addr:100.8.73.88  Bcast:100.8.73.255  Mask:255.255.255.0
          inet6 addr: fe80::6e92:bfff:fe2b:cc2e/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:58341092 errors:0 dropped:0 overruns:0 frame:0
          TX packets:11905856 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:9817032348 (9.1 GiB)  TX bytes:2293637883 (2.1 GiB)

eth1      Link encap:Ethernet  HWaddr 6C:92:BF:2B:CC:2F  
          inet addr:192.168.1.1  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::6e92:bfff:fe2b:cc2f/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:370648 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:23161750 (22.0 MiB)  TX bytes:552 (552.0 b)

eth2      Link encap:Ethernet  HWaddr 6C:92:BF:2B:CC:30  
          inet6 addr: fe80::6e92:bfff:fe2b:cc30/64 Scope:Link
          UP BROADCAST RUNNING PROMISC MULTICAST  MTU:2000  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 b)  TX bytes:468 (468.0 b)

 

awk 提取eth0的IP

[root]# ifconfig | awk -v flag=0 '{if ($1 == "eth0") {flag=1;next} if (flag == 1) {print $2;flag=0}}' | awk -F: '{print $2}'
100.8.73.88

 

执行逻辑:

从第一行开始检查,如果找到eth0,那么flag赋值1,并且跳过后面语句直接处理下一行。

如果没有找到eth0,那么判断flag是否等于1。若flag等于1,那么打印出来含有IP地址的字符串 addr:100.8.73.88 。

将冒号当做分割符,打印出来干净的IP地址 100.8.73.88 。

posted @ 2022-12-27 16:08  超级宝宝11  阅读(104)  评论(0编辑  收藏  举报