您的位置:首页 > 运维架构 > Shell

leetcode-shell-192. Word Frequency

2016-06-16 16:03 411 查看
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


题意:统计词的频率
思路:
最开始想创建数组来记录词出现的频率,但是遍历成本高,后来看了别人的方法,使用awk工具就可以
最终shell脚本:
cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -rn | awk '{print $2" "$1}'

tr 表示用什么切分单词,有点儿像split函数,后面跟空格和回车,表示我们通过空格和回车切分单词
sort 用来排序
uniq去重,-c用来统计个数
sort -rn -rn表示用数值倒序排序
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: