如果我拥有来自ip addr | grep ether -B1
的数据,请设置。
11: vnet0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 500
link/ether fe:54:4c:8e:df:f0 brd ff:ff:ff:ff:ff:ff
12: vnet1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 500
link/ether fe:54:7a:d0:1a:04 brd ff:ff:ff:ff:ff:ff
13: vnet2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 500
link/ether fe:54:00:29:ef:0c brd ff:ff:ff:ff:ff:ff
14: vnet3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 500
link/ether fe:54:be:c6:c3:32 brd ff:ff:ff:ff:ff:ff
15: vnet4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 500
link/ether fe:54:e8:cf:ff:ef brd ff:ff:ff:ff:ff:ff
我想将其概括为<interface> <hwaddr>
:
vnet0 fe:54:4c:8e:df:f0
vnet1 fe:54:7a:d0:1a:04
vnet2 fe:54:00:29:ef:0c
vnet3 fe:54:be:c6:c3:32
vnet4 fe:54:e8:cf:ff:ef
我可以使用{b}命令与sed
或awk
来实现此目的吗?
提前谢谢!
答案 0 :(得分:1)
一个简单的awk脚本可以达到目的。
awk '$2~/vnet[0-4]/{inter=$2; next} {print inter,$2}' inputFile
将产生输出
vnet0: fe:54:4c:8e:df:f0
vnet1: fe:54:7a:d0:1a:04
vnet2: fe:54:00:29:ef:0c
vnet3: fe:54:be:c6:c3:32
vnet4: fe:54:e8:cf:ff:ef
它做什么?
$2~/vnet[0-4]/
检查第二列$2
是否计算模式vnet[0-4]
,如果是,
inter=$2; next
将接口分配给inter
变量,next
会导致awk读取下一条记录而不考虑剩余的操作。
print inter,$2
打印interface和hwaddr
答案 1 :(得分:1)
通过awk,
$ awk '/^[0-9]+: +/{split($2,a,":");var=a[1];next}{print var,$2}' file
vnet0 fe:54:4c:8e:df:f0
vnet1 fe:54:7a:d0:1a:04
vnet2 fe:54:00:29:ef:0c
vnet3 fe:54:be:c6:c3:32
vnet4 fe:54:e8:cf:ff:ef
<强>解释强>
/^[0-9]+: +/
如果一行以一个或多个数字开头,后跟冒号加一个或多个空格,则执行块{}
split($2,a,":");
根据分隔符:
拆分第2列的值,然后将其存储到关联数组a
var=a[1];
将数组索引1的值存储到变量var
。也就是说,它会将vnet\d+
存储到变量var
next
下一个语句强制awk立即停止处理当前记录并继续下一条记录。这意味着不会对当前记录执行进一步的规则,并且不会执行当前规则的其余操作。 {print var,$2}
打印存储在变量var
中的值加上下一行的第2列值。
答案 2 :(得分:1)
这可能适合你(GNU sed):
sed -r 'N;s/\S+\s+(\S+):.*(..:..:..:..:..:..) .*/\1 \2/' file
一次读取两行并使用模式匹配/反向引用来提取所需的数据。