码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2016-04-03 00:22:24      阅读:740      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!