标签:
新来个intern,跟着某同事做devops,看其对于shell有点疑惑,于是列举了个简单的应用给他,统计IP出现次数 。
TCP 192.168.0.97:1052 60.28.216.15:80 CLOSE_WAIT TCP 192.168.0.97:1436 219.133.60.243:8000 CLOSE_WAIT TCP 192.168.0.97:1624 72.14.235.101:443 CLOSE_WAIT TCP 192.168.0.97:1773 192.168.0.2:8000 ESTABLISHED TCP 192.168.0.97:2181 207.46.110.37:1863 ESTABLISHED TCP 192.168.0.97:2187 64.4.37.41:1863 ESTABLISHED TCP 192.168.0.97:2188 207.46.27.162:1863 ESTABLISHED TCP 192.168.0.97:2406 219.133.49.80:443 CLOSE_WAIT TCP 192.168.0.97:4127 192.168.0.165:2120 ESTABLISHED TCP 192.168.0.97:4142 192.168.0.165:2138 ESTABLISHED TCP 192.168.0.97:4147 219.133.63.142:443 CLOSE_WAIT
统计第三列中ip出现的次数,并排序取前五个ip
shell可以这么搞:
cat ip.txt |tr -s ‘ ‘| cut -d ‘ ‘ -f 3|cut -d : -f 1 | sort |uniq -c | head -n 5
带awk可以这么搞:
awk ‘{print $3}‘ ip.txt |cut -d : -f 1 | sort |uniq -c | head -n 5
要是没有端口号的话,直接用awk也能完成统计:
awk ‘{a[$4]++}END{for(i in a){if(a[i]>0){print a[i],i}}}‘ ip.txt |sort -nr | head -n 5
标签:
原文地址:http://my.oschina.net/u/921876/blog/420561