使用 sed 和/或 grep 仅列出 ifconfig 输出中具有“parent: eth0”字段的 iface 接口名称

使用 sed 和/或 grep 仅列出 ifconfig 输出中具有“parent: eth0”字段的 iface 接口名称

ifconfig输出:

lo: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 33192
        inet 127.0.0.1 netmask 0xff000000
        inet6 ::1 prefixlen 128
        inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
eth0: flags=8b43<UP,BROADCAST,RUNNING,PROMISC,ALLMULTI,SIMPLEX,MULTICAST> mtu 1500
        address: 01:02:03:04:05:06
        media: Ethernet 1000baseT full-duplex
        status: active
        inet 192.168.0.10 netmask 0xffff0000 broadcast 192.254.255.255
        inet alias 0.0.0.0 netmask 0xff000000 broadcast 255.255.255.255
        inet6 fe80::0:0:0:01%eth0 prefixlen 64 scopeid 0x4
vlan01: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
        vlan: 01 priority: 0 parent: eth0
        address: 01:02:03:04:05:06
        inet 192.168.0.11 netmask 0xfffffff0 broadcast 192.254.255.255
        inet6 fe80::0:0:0:02%vlan01 prefixlen 64 scopeid 0x6
        inet6 2a03:0:0:0::e1 prefixlen 64

请注意,vlan01有一个记录“parent: eth0”。我需要获取vlan01这个特定的输出。我只有sed并且grep可供我使用。

有可能吗ifconfig -a | sed '...'

答案1

我们可以用 sed 来做到这一点:

#!/bin/sed -nf

# If it begins with anything except whitespace, trim it down to the
# bit before ":", and store that into hold space.
/^[^ ]/{
s/:.*//
h
}

# If we see "parent: eth0", then print the hold space.
/parent: eth0/{
g
p
}

根据您的输入,它将输出vlan01(和换行符)。

答案2

仅使用grep

ifconfig | grep -B1 parent | grep -oh ^[a-z0-9]*
# -B num - Print num lines of leading context before matching lines.
# -o Print only the matched (non-empty) parts of matching lines, with each such part on a separate output line.

这将vlan01输出您问题中提供的输出。请注意,我的示例仅查找parent。模式应更新以反映您想要的内容 -parent: eth0或其他内容。

相关内容