首页 > 系统服务 > 详细

Shell练习 统计单词个数,降序排列

时间:2016-04-03 00:19:51      阅读:564      评论:0      收藏:0      [点我收藏+]
原文:https://leetcode.com/problems/word-frequency/
Write a bash script to calculate the frequency of each word in a text file words.txt.

For simplicity sake, you may assume:

words.txt contains only lowercase characters and space ‘ ‘ characters.
Each word must consist of lowercase characters only.
Words are separated by one or more whitespace characters.
For example, assume that words.txt has the following content:

the day is sunny the the
the sunny is is
Your script should output the following, sorted by descending frequency:
the 4
is 3
sunny 2
day 1

简单点就是说给你一个文件,里面是又空格【可以有多个】分割好的单词【都是小写】,请统计一下不同单词的个数,并降序输出。

 

将单词记录到数组中,之后遍历输出,使用sort排序,指定第2列按数字降序,即可。

答案:

awk ‘{for(i=1;i<=NF;i++) num[$i]++;} END{ for(k in num) print k" "num[k]}‘  words.txt|sort -rnk 2

 

使用sort排序,指定哪一列使用-k,后面跟数字,按数字进行排序,使用-n,降序排列使用-r。

 

Shell练习 统计单词个数,降序排列

原文:http://www.cnblogs.com/xiaoxian1369/p/5348645.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!