在日常Linux操作常常需要對一些文件或屏幕數次中重復的字段進行分組統計。另外分組統計也是常考的面試題之一。
實現的方法非常簡單,核心命令為:sort | uniq --c | sort -rn
。
- sort:對指定列進行排序,使該列相同的字段排練到一起
- uniq -c:uniq命令用於檢查及刪除文本文件中重復出現的行列,
uniq -c
或uniq --count
用於統計重復的行 - sort -rn:
sort -n
將字符串數字按數字進行比較,-r
則從大到小排列
題目1. 某個文本demo.txt文件,每一行一個單詞,統計出現次數最多的3個單詞
hello
hi
hello
world
world
my
word
hi
hello
參考答案
sort demo.txt | uniq -c | sort -rn | head -3
執行結果如下
3 hello
2 world
2 hi
題目2. 統計Nginx日志access.log中出現最多的10個url
201.158.69.116 - - [03/Jan/2013:21:17:20 -0600] fwf[-] tip[-] 127.0.0.1:9000 0.007 0.007 MX pythontab.com GET /html/test.html HTTP/1.1 "200" 2426 "http://a.com" "es-ES,es;q=0.8" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"
187.171.69.177 - - [03/Jan/2013:21:17:20 -0600] fwf[-] tip[-] 127.0.0.1:9000 0.006 0.006 MX pythontab.com GET /html/test2.html HTTP/1.1 "200" 2426 "http://a.com" "es-ES,es;q=0.8" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"
參考答案
cat access.log | awk '{print $14}'|sort|uniq -c | sort -rn | head -10
或
sort access.log -k 14 | uniq -c | sort -rn | head -10| awk '{print $1,$15}'
sort
-k
:指定列-t
:指定分隔符
執行結果如下
1 /html/test2.html
1 /html/test.html
題目3. 統計80端口,TCP鏈接狀態,並按數量從大到小排序
netstat -nat | grep 80
顯示如下:
tcp4 0 0 192.168.0.101.57581 80.254.145.118.80 SYN_SENT
tcp4 0 0 192.168.0.101.57572 111.161.64.23.80 ESTABLISHED
tcp4 0 0 192.168.0.101.57565 60.29.242.162.80 ESTABLISHED
tcp4 0 0 192.168.0.101.57513 175.174.56.212.80 CLOSE_WAIT
tcp6 0 0 fe80::18e3:52d8:.56850 fe80::1cc0:75be:.62835 ESTABLISHED
tcp4 0 0 192.168.0.101.56178 175.174.56.212.80 CLOSE_WAIT
參考答案
netstat -nat | grep 80 | awk '{print $6}' | sort | uniq -c | sort -rn
執行結果如下
27 ESTABLISHED
10 LISTEN
2 CLOSE_WAIT
1 ce382f50fea83507
1 ce382f50fea80df7
1 SYN_SENT
1