获取每个ip地址/ ifconfig接口命令的前3行Linux

时间:2018-08-01 09:05:34

标签: linux ifconfig ipconfig

我正在尝试从某些VM中获取IP地址/ ifconfig的前三行-其中一些在Ubuntu上运行,某些在CentOS上运行。

例如:

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 9001
        inet 172.31.106.100  netmask 255.255.240.0  broadcast 172.31.111.255
        inet6 fe80::10c5:1dff:fec0:803e  prefixlen 64  scopeid 0x20<link>
        ether 12:c5:1d:c0:80:3e  txqueuelen 1000  (Ethernet)
        RX packets 7483  bytes 7706844 (7.3 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 2998  bytes 470781 (459.7 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 12100  bytes 3865475 (3.6 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 12100  bytes 3865475 (3.6 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

从这行代码中,我只需要获得以下部分:

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 9001
        inet 172.31.106.100  netmask 255.255.240.0  broadcast 172.31.111.255
        inet6 fe80::10c5:1dff:fec0:803e  prefixlen 64  scopeid 0x20<link>

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>

ip地址命令也应如此。 有什么办法可以使用Linux命令来实现这一目标吗?

非常感谢,

罗曼

1 个答案:

答案 0 :(得分:0)

您可以使用sed来做到这一点,

ifconfig | sed -En '/^[^[:space:]]/,+2p; /^[[:space:]]*$/p'

简要说明,

  • 流水线结果将由sed
  • 处理
  • /^[^[:space:]]/,+2p:搜索并打印不以空格开头的行,并打印以下两行
  • /^[[:space:]]*$/p:搜索并打印空白行