我正在使用shell脚本对URL进行多次迭代的nslookup。我需要检查每个URL返回IP的次数。
在输出文件中,输出存储为
URL
IP address
使用uniq -c命令当相同的IP地址相邻时我得到计数,但是当相同的IP地址在非相邻的行上时,我得到计数
Command is
cat file.log | awk '{print $1}' | uniq -c
这是示例输出
1 url
3 72.51.46.230
现在,如果为特定URL返回多个IP地址,并且它们位于非相邻行,因为我没有运行。迭代。在这种情况下,uniq-c命令将不起作用。如果我使用排序选项它排序但我需要显示每个URL的输出,即。带有计数及其IP地址的URL和下一行。
例如。如果我在google.com上做nslookup它将返回多个地址,我会执行uniq -c我得到以下输出。如您所见,IP地址相同但计数仅为1,因为uniq -c不适用于非相邻线路。
1 74.125.236.64
1 74.125.236.78
1 74.125.236.67
1 74.125.236.72
1 74.125.236.65
1 74.125.236.73
1 74.125.236.70
1 74.125.236.66
1 74.125.236.68
1 74.125.236.71
1 74.125.236.69
1 nslookup: can't resolv 'google.com'
1 nslookup: can't resolv 'google.com'
1 nslookup: can't resolv 'google.com'
1 nslookup: can't resolv 'google.com'
1 nslookup: can't resolv 'google.com'
1 nslookup: can't resolv 'google.com'
1 nslookup: can't resolv 'google.com'
1 74.125.236.70
1 74.125.236.66
1 74.125.236.68
1 74.125.236.71
1 74.125.236.69
我也尝试过使用AWK,但在这种情况下输出没有按照我的要求进行格式化。
Awk命令
awk '{a[$0]++}END{for (i in a) printf "%-2d -> %s \n", a[i], i}' file.log
您能否提出更好的解决方案来实现这一目标 - 以上述格式获取计数和显示?
所需的输出格式是
URL
Count IP address
示例输入文件。
URL1
72.51.46.230
72.51.46.230
google.com
74.125.236.64
74.125.236.78
(null)
nslookup: can't resolv 'google.com'
nslookup: can't resolv 'google.com'
nslookup: can't resolv 'google.com'
nslookup: can't resolv 'google.com'
nslookup: can't resolv 'google.com'
需要样本输出
URL1
2 72.51.46.230
google.com
1 74.125.236.64
1 74.125.236.78
1 null
5 nslookup: can't resolv 'google.com'
谢谢。
答案 0 :(得分:1)
以下awk
脚本完成工作:
$1~/[a-z]+[.].*/{ # If line have a letter in must be a URL
for(i in ip) # Print all the counts and IPs (empty first time)
print ip[i],i
delete ip # Delete array for next set of IP's
print # Print the URL
next # Skip to next line
}
{
ip[$0]++ # If here line contains IP, increment the count per IP
}
END{ # Reached end of file need to print the last set of IPs
for(i in ip)
print ip[i],i
}
将其另存为script.awk
并运行如下:
$ awk -f script.awk file
creativecommons.org
2 72.51.46.230
google.com
5 nslookup: can't resolv 'google.com'
1 (null)
1 74.125.236.64
1 74.125.236.78
答案 1 :(得分:0)
尝试使用第一个命令但添加sort
:
awk '{print $1}' file.log | sort | uniq -c
答案 2 :(得分:0)
你可以直接使用:
awk '{a[$1]++}END{for(i in a)print a[i],i}' file.log
而不是多个命令并管道每个命令的输出。
如果你想要它没有awk:
cut -f1 -d"\t" file.log|sort|uniq-c
会做