uniq -c 不适用于 awk?

uniq -c is not working with awk?

我有一个包含多个数据的日志文件,我想从该文件中过滤 DHCPREQUEST IP,我想计算日志文件中针对该服务内容的 IP 请求有多少次是这样的:-

Mar 22 11:20:34 DHCP-IP dhcp: DHCPREQUEST for 10.1.1.1 from aa:00:00:00:00:00 (pc) via 10.1.1.2
Mar 22 11:19:34 DHCP-IP dhcp: DHCPREQUEST for 10.1.1.2 from aa:00:00:00:00:00 (pc) via 10.1.1.2
Mar 22 11:18:34 DHCP-IP dhcp: DHCPREQUEST for 10.1.1.2 from aa:00:00:00:17:00 (pc) via 10.1.1.2
Mar 22 11:16:34 DHCP-IP dhcp: DHCPREQUEST for 10.1.1.1 from aa:00:00:00:00:00 (pc) via 10.1.1.2
Mar 22 11:15:34 DHCP-IP dhcp: DHCPREQUEST for 10.1.1.1 from aa:00:00:00:00:00 (pc) via 10.1.1.2
Mar 22 11:14:34 DHCP-IP dhcp: DHCPREQUEST for 10.1.1.1 from aa:00:00:00:00:00 (pc) via 10.1.1.2
Mar 22 11:12:34 DHCP-IP dhcp: DHCPREQUEST for 10.1.1.1 from aa:00:00:00:00:00 (pc) via 10.1.1.2
Mar 22 11:11:34 DHCP-IP dhcp: DHCPREQUEST for 10.1.1.1 from aa:00:00:00:00:00 (pc) via 10.1.1.2

使用此代码,我正在使用 grep IP 打印计数,但它显示重复 IP 的计数为 1,请指出我做错了什么

five_min='Mar 22 11:15:34' 
while IFS= read -r line; do
    if [[ "$five_min" < "$line" ]] 
    then
        echo "$line" | grep DHCPREQUEST  | awk -F  " " '{print  }' | uniq -c
    fi
done < file.txt

你是 运行 单行命令,所以你得到 1 是有道理的。

具有以下test.txt:

Mar 22 11:20:34 DHCP-IP dhcp: DHCPREQUEST for 10.1.1.1 from aa:00:00:00:00:00 (pc) via 10.1.1.2
Mar 22 11:20:35 DHCP-IP dhcp: DHCPREQUEST for 10.1.1.1 from aa:00:00:00:00:00 (pc) via 10.1.1.2
Mar 22 11:20:36 DHCP-IP dhcp: DHCPREQUEST for 10.1.1.1 from aa:00:00:00:00:00 (pc) via 10.1.1.2

命令:

grep DHCPREQUEST test | awk '{print }' | uniq -c

打印:

3 10.1.1.1

关注单个 awk 也可能对您有所帮助。

awk 'match([=10=],/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/){array[substr([=10=],RSTART,RLENGTH)]++} END{for(i in array){print array[i],i}}'  Input_file

现在也添加 non-one 线性形式的解决方案。

awk '
match([=11=],/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/){  array[substr([=11=],RSTART,RLENGTH)]++  }
END{
  for(i in array)                         {  print array[i],i                    }
}
'   Input_file