awk数组统计

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

处理以下文件内容,将域名取出并根据域名进行计数排序处理:(百度和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

思路:

取出域名

以斜线为菜刀取出第二列(域名)

进行加工

创建一个数组

把第二列(域名)作为数组的下标

通过类似于i++的形式进行计算数量

统计后把结果输出

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[

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

转载于:https://www.cnblogs.com/jmaly/p/6689310.html

编程小号
上一篇 2025-02-17 13:11
下一篇 2025-03-03 12:51

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/138677.html