awk數組統計


處理以下文件內容,將域名取出並根據域名進行計數排序處理:(百度和sohu面試題)

1 http://www.etiantian.org/index.html
2 http://www.etiantian.org/1.html
3 http://post.etiantian.org/index.html
4 http://mp3.etiantian.org/index.html
5 http://www.etiantian.org/3.html
6 http://post.etiantian.org/2.html

要求結果:

mp3.etiantian.org 1
post.etiantian.org 2
www.etiantian.org 3

思路:

  1. 取出域名

    1.  以斜線為菜刀取出第二列(域名)

  1. 進行加工

    1. 創建一個數組

    2. 把第二列(域名)作為數組的下標

    3. 通過類似於i++的形式進行計算數量

  2. 統計后把結果輸出

 

1、查看需要處理的文件

1 [root@martin ~]# cat test.txt 
2 http://www.etiantian.org/index.html
3 http://www.etiantian.org/1.html
4 http://post.etiantian.org/index.html
5 http://mp3.etiantian.org/index.html
6 http://www.etiantian.org/3.html
7 http://post.etiantian.org/2.html

2、以斜線為分割符,取出第二列,+表示連續的。

1 [root@martin ~]# awk -F "/+" '{print $2}' test.txt 
2 www.etiantian.org
3 www.etiantian.org
4 post.etiantian.org
5 mp3.etiantian.org
6 www.etiantian.org
7 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.org
4 www.etiantian.org
5 post.etiantian.org
6 mp3.etiantian.org
7 www.etiantian.org
8 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 1
4 www.etiantian.org 2
5 post.etiantian.org 1
6 mp3.etiantian.org 1
7 www.etiantian.org 3
8 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.txt
2 mp3.etiantian.org 1
3 post.etiantian.org 2
4 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 -t
3 mp3.etiantian.org   1
4 post.etiantian.org  2
5 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                        6
10 history                      6
11 /etc/rc.d/init.d/keepalived  5

 

本文參考自 “李導的博客” 博客,原地址http://lidao.blog.51cto.com/3388056/1912219


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM