leetcode bash题--统计词频

发布时间 2023-05-10 11:21:31作者: zed99

写一个 bash 脚本以统计一个文本文件 words.txt 中每个单词出现的频率。

为了简单起见,你可以假设:

words.txt只包括小写字母和 ' ' 。
每个单词只由小写字母组成。
单词间由一个或多个空格字符分隔。
示例:

假设 words.txt 内容如下:

the day is sunny the the
the sunny is is


你的脚本应当输出(以词频降序排列):

the 4
is 3
sunny 2
day 1

思路: 

先将文本输出成一列,再使用sort命令将相同的词放在一次,uniq -c算出词数,再sort按次数排序,最后awk换列顺序

[root@jay bash_practise]# cat words.txt |xargs -n1|sort |uniq -c|sort -r |awk '{print $2 " " $1}'
the 4
is 3
sunny 2
day 1