根据某一行解析唯一字符串

根据某一行解析唯一字符串

我有一个 dhcpd.leases 文件,其中包含以下内容:

lease 172.231.100.152 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41; 
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state active;
next binding state expired;

lease 172.231.100.152 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41; 
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state active;
next binding state expired;

lease 172.231.100.152 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41; 
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state free;
next binding state expired;

lease 172.231.100.151 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41; 
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state active;
next binding state expired;

lease 172.231.100.152 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41; 
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state free;
next binding state expired;

正如您在该文件中可能知道的那样,某些租约会被多次记录。我需要一个解决方案,仅使用 172.231.100 来 grep 出唯一的 IP 地址范围,但仅限绑定状态为活动的 IP 地址范围。我知道有一些脚本可以使用 DHCP 为您执行此操作,但我们的脚本无法使用 atm,因此如果有一个命令行解决方案就非常好。请注意,“绑定状态”行始终是“租用”行的第六行。

答案1

awk解决方案:

awk '/^lease/ && !($2 in ips){ f=1; ips[$2]=$0; n=NR+5 }
     f && NR <= n{ 
         a[++c]=$0; 
         if (NR == n) { 
             if ($NF == "active;") { 
                 for (i=1; i<7; i++) print a[i]; print "" 
             } 
             c=0 
         } 
     }' dhcpd.leases

输出:

lease 172.231.100.152 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41; 
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state active;

lease 172.231.100.151 {
starts 2 2017/11/14 14:50:41;
ends 2 2017/11/14 15:20:41; 
tstp 2 2017/11/21 15:05:41;
cltt 2 2017/11/14 14:50:41;
binding state active;

相关内容