gpt4 book ai didi

linux - 解析大括号中的 block

转载 作者:太空狗 更新时间:2023-10-29 12:24:41 26 4
gpt4 key购买 nike

我正在尝试解析如下所示的 dhcpd.conf 文件:

authoritative;

subnet x.x.x.x netmask x.x.x.x {
range x.x.x.x x.x.x.x;
deny unknown-clients;
default-lease-time 86400;
max-lease-time 86400;
option domain-name "bla";
option domain-name-servers x.x.x.x;
option broadcast-address x.x.x.x;
option subnet-mask x.x.x.x;
option routers x.x.x.x;

host host1 {
hardware ethernet 00:e1:4c:68:00:53;
fixed-address 1.1.1.1;
}

host host2 {
hardware ethernet 01:e2:4d:69:01:54;
fixed-address 2.2.2.2;
}

host host3 {
hardware ethernet 02:e3:4e:70:02:55;
fixed-address 3.3.3.3;
}

host host4 {
hardware ethernet 03:e4:4f:71:03:56;
fixed-address 4.4.4.4;
}

host host5 {
hardware ethernet 04:e5:5f:72:04:57;
fixed-address 5.5.5.5;
}
}

最后,我需要遍历主机 block (无论它们的名称如何)并将 MAC 地址和 IP 地址分配给变量以处理组合。到目前为止,我设法只使用一个变量来做到这一点:

for MAC in `cat /etc/dhcp/dhcpd.conf | grep "hardware ethernet" | awk '{ print $3 }' | tr ";" " "`
do
echo "Found MAC address: " $MAC "Found IP: <I need the IP Variable here...>"
done

也许以某种方式“grep”主机 block 以便循环遍历这些 block 会更好,但我不知道该怎么做。

谁能给我一个提示,告诉我如何做到这一点?

谢谢

最佳答案

鉴于输入文件的格式完全相同(MAC 后跟 IP),sed 后的一行将给出“MAC、IP”csv 对列表。你可以解析它并做任何你想做的事。

sed -n '/\s*hardware ethernet/{s/\s*hardware ethernet \(.*\);/\1/;N;s/\([a-z0-9:]*\)\s*fixed-address \(.*\);/\1,\2/p}' /etc/dhcp/dhcpd.conf

输出:

00:e1:4c:68:00:53,1.1.1.1
01:e2:4d:69:01:54,2.2.2.2
02:e3:4e:70:02:55,3.3.3.3
03:e4:4f:71:03:56,4.4.4.4
04:e5:5f:72:04:57,5.5.5.5

要生成与示例中一样的准确输出,

sed -n '/\s*hardware ethernet/{s/\s*hardware ethernet \(.*\);/\1/;N;s/\([a-z0-9:]*\)\s*fixed-address \(.*\);/Found MAC address: \1, Found IP: \2/p}' /etc/dhcp/dhcpd.conf

输出:

Found MAC address: 00:e1:4c:68:00:53, Found IP: 1.1.1.1
Found MAC address: 01:e2:4d:69:01:54, Found IP: 2.2.2.2
Found MAC address: 02:e3:4e:70:02:55, Found IP: 3.3.3.3
Found MAC address: 03:e4:4f:71:03:56, Found IP: 4.4.4.4
Found MAC address: 04:e5:5f:72:04:57, Found IP: 5.5.5.5

编辑

您可以从每一对中提取 MAC 和 IP,并按如下方式使用它们。

for v in $(sed -n '/\s*hardware ethernet/{s/\s*hardware ethernet \(.*\);/\1/;N;s/\([a-z0-9:]*\)\s*fixed-address \(.*\);/\1,\2/p}' /etc/dhcp/dhcpd.conf); do
mac="${v%,*}"
ip="${v#*,}"
echo "MAC: $mac"
echo "IP: $ip"
done

关于linux - 解析大括号中的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45586363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com