shell 文本单词计数

words.txt中的内容如下:

the       day is  sunny the  the  
 the sunny is is

统计每个单词出现的次数,并降序输出。

Unix Pipes脚本如下:

cat words.txt | tr -s ' ' '
' | sort | uniq -c | sort -r | awk '{print $2, $1}'

脚本解释:

tr -s ' ' '
'       

表示:连续出现的空格只保留一个,并在空格处以换行符分割文本
sort

表示:对输出文本进行排序
uniq -c

表示:对连续出现的重复的行进行计数
sort -r

表示:对输出文本进行降序排序
awk '{print $2, $1}'

表示:打印出文本的第二列和第一列

最终输出结果如下:

the 4
is 3
sunny 2
day 1
原文地址:https://www.cnblogs.com/lasclocker/p/4584483.html