awk數組統計,awk數組
處理以下檔案內容,將網域名稱取出並根據網域名稱進行計數排序處理:(百度和sohu面試題)
1 http://www.etiantian.org/index.html2 http://www.etiantian.org/1.html3 http://post.etiantian.org/index.html4 http://mp3.etiantian.org/index.html5 http://www.etiantian.org/3.html6 http://post.etiantian.org/2.html
要求結果:
mp3.etiantian.org 1post.etiantian.org 2www.etiantian.org 3
思路:
取出網域名稱
以斜線為菜刀取出第二列(網域名稱)
進行加工
建立一個數組
把第二列(網域名稱)作為數組的下標
通過類似於i++的形式進行計算數量
統計後把結果輸出
1、查看需要處理的檔案
1 [root@martin ~]# cat test.txt 2 http://www.etiantian.org/index.html3 http://www.etiantian.org/1.html4 http://post.etiantian.org/index.html5 http://mp3.etiantian.org/index.html6 http://www.etiantian.org/3.html7 http://post.etiantian.org/2.html
2、以斜線為分割符,取出第二列,+表示連續的。
1 [root@martin ~]# awk -F "/+" '{print $2}' test.txt 2 www.etiantian.org3 www.etiantian.org4 post.etiantian.org5 mp3.etiantian.org6 www.etiantian.org7 post.etiantian.org
3、建立數組和進行統計
1 [root@martin ~]# awk -F "/+" '{hotel[$2]}' test.txt #建立數組2 [root@martin ~]# awk -F "/+" '{hotel[$2];print $2}' test.txt #建立數組,並通過print 輸出元素名字3 www.etiantian.org4 www.etiantian.org5 post.etiantian.org6 mp3.etiantian.org7 www.etiantian.org8 post.etiantian.org
1 [root@martin ~]# awk -F "/+" '{hotel[$2]++}' test.txt #對數組相同下標的數組進行計數統計2 [root@martin ~]# awk -F "/+" '{hotel[$2]++;print $2,hotel[$2]}' test.txt #通過print輸出元素名字和統計數3 www.etiantian.org 14 www.etiantian.org 25 post.etiantian.org 16 mp3.etiantian.org 17 www.etiantian.org 38 post.etiantian.org 2
$2表示的是每一行的第二列,是一個變數;hotel[$2]++這種形式類似於i++,只不過把變數i換成了數組hotel[$2]
4、統計完畢後再用for迴圈列印輸出數組不同下表和對應統計數
1 [root@martin ~]# awk -F "/+" '{hotel[$2]++}END{for(pole in hotel) print pole,hotel[pole]}' test.txt2 mp3.etiantian.org 13 post.etiantian.org 24 www.etiantian.org 3
1 最佳化顯示,格式化輸出2 [root@martin ~]# awk -F "/+" '{hotel[$2]++}END{for(pole in hotel) print pole,hotel[pole]}' test.txt|sort -k2|column -t3 mp3.etiantian.org 14 post.etiantian.org 25 www.etiantian.org 3
5、統計linux系統的history記錄使用前10的命令
1 [root@martin ~]# history|awk '{order[$2]++}END{for(n in order) print n,order[n]}'|sort -rnk2|head|column -t 2 awk 54 3 history|awk 44 4 [ 22 5 ll 19 6 rpm 12 7 yum 8 8 w 6 9 uname 610 history 611 /etc/rc.d/init.d/keepalived 5
本文參考自 “李導的部落格” 部落格,原地址http://lidao.blog.51cto.com/3388056/1912219