基本上,我有一个来自DHCP服务器日志的输出,如下所示:
hardware ethernet 00:16:41:ef:9e:47;
client-hostname "mo-10";
hardware ethernet 00:11:25:73:20:a5;
client-hostname "mo-11";
hardware ethernet 00:11:25:73:20:a5;
client-hostname "mo-11";
hardware ethernet 00:11:25:73:20:a5;
client-hostname "mo-11";
hardware ethernet 00:16:41:ef:9e:47;
client-hostname "mo-10";
hardware ethernet 00:11:25:73:21:35;
client-hostname "mo-23";每两行连接在一起-第一行是网络上设备的MAC地址,第二行是主机名。我想获取列表,并将每一对行放入dhcp服务器的配置块中,如下所示:
host mo-10 {
hardware ethernet 00:16:41:ef:9e:47;
fixed-address 192.168.1.10;
}主机后部分应与客户端主机名相同,硬件以太网块应相同,固定地址应始终为192.168.1.x,其中x是主机名中的编号(因此对于主机mo-10,ip应为192.168.1.10,mo-23为192.168.1.23 )。所有的东西都应该放在花括号里。此外,还有许多重复的条目,我想删除。我试着和grep和awk混在一起,但我不太擅长在bash中处理文本,这对我来说太复杂了。如果有人能提供一种方法来完成这一任务,并解释它的工作原理,我将非常高兴。
非常感谢。
发布于 2014-08-22 17:00:27
这里有一种方法:
awk '
NR%2 { eth = $0; next }
{ gsub(/[";]/,""); map[$NF] = eth }
END {
for (host in map) {
split (host, t, /-/);
print "host " host " {\n\t" map[host], RS, "\tfixed-ethernet 192.168.1."t[2]";" RS "}"
}
}' file
host mo-10 {
hardware ethernet 00:16:41:ef:9e:47;
fixed-ethernet 192.168.1.10;
}
host mo-11 {
hardware ethernet 00:11:25:73:20:a5;
fixed-ethernet 192.168.1.11;
}
host mo-23 {
hardware ethernet 00:11:25:73:21:35;
fixed-ethernet 192.168.1.23;
}将奇数行存储在变量eth中。对于偶数行,移除引号和;,并在主机名处创建一个具有行值的散列键。在END块中,迭代散列并在-上拆分主机名。
然后,您只需打印作为您想要的输出。
发布于 2014-08-22 17:01:22
你可以用sed。为了去除重复的物品,我建议使用一个管道:
sed '/hardware/{N;s/\n/ /}' < list | sort -k5 | uniq -f4 | sed -r 's/ *hardware ([^ ]*) ([^;]*); *.*"(.*\-(.*))";/host \3 {\n\thardware \1 \2;\n\tfixed-address 192.178.10.\4;\n}/'管道将两行记录按每条记录平放成一行,然后将它们交给排序/uniq,然后再交给sed进行最终的格式化。
输出:
host mo-10 {
hardware ethernet 00:16:41:ef:9e:47;
fixed-address 192.178.10.10;
}
host mo-11 {
hardware ethernet 00:11:25:73:20:a5;
fixed-address 192.178.10.11;
}
host mo-23 {
hardware ethernet 00:11:25:73:21:35;
fixed-address 192.178.10.23;
}顺便说一句,毕竟我更喜欢awk解决方案,因为它不需要一次又一次地迭代数据。(在给出这个答案的第一个版本时,没有读取删除重复项的限制)。
发布于 2014-08-22 17:01:41
下一个:
perl -lanE '
if(/^\s*$/){$.--;next} #skip empty lines
push @v, map {s/[^\da-f:]//ig;$_} $F[$.%2+1] }{ %h=@v; #process
#print
say qq[host mo-$h{$_} {
hardware ethernet $_;
fixed-address 192.168.1.$h{$_};
}] for keys %h
' <<EOF
hardware ethernet 00:16:41:ef:9e:47 ;
client-hostname "mo-10" ;
hardware ethernet 00:11:25:73:20:a5;
client-hostname "mo-11" ;
hardware ethernet 00:11:25:73:20:a5 ;
client-hostname "mo-11";
hardware ethernet 00:11:25:73:20:a5;
client-hostname "mo-11";
hardware ethernet 00:16:41:ef:9e:47;
client-hostname "mo-10";
hardware ethernet 00:11:25:73:21:35;
client-hostname "mo-23";
EOF版画
host mo-23 {
hardware ethernet 00:11:25:73:21:35;
fixed-address 192.168.1.23;
}
host mo-10 {
hardware ethernet 00:16:41:ef:9e:47;
fixed-address 192.168.1.10;
}
host mo-11 {
hardware ethernet 00:11:25:73:20:a5;
fixed-address 192.168.1.11;
}https://stackoverflow.com/questions/25451984
复制相似问题