Shell统计每个单词出现的个数

题目链接

题目描述
写一个 bash脚本以统计一个文本文件 nowcoder.txt 中每个单词出现的个数。

为了简单起见,你可以假设:
nowcoder.txt只包括小写字母和空格。
每个单词只由小写字母组成。
单词间由一个或多个空格字符分隔。

示例:
假设 nowcoder.txt 内容如下:
welcome nowcoder
welcome to nowcoder
nowcoder
你的脚本应当输出(以词频升序排列):
to 1
welcome 2
nowcoder 3

说明:
不要担心个数相同的单词的排序问题,每个单词出现的个数都是唯一的。

思路
把文本换成每个单词占用一行, 排序, 然后去重得到每个单词出现次数, 再排序, 最后 awk 输出即可

cat nowcoder.txt | tr -s ' ' '
' | sort | uniq -c | sort | awk '{print $2" "$1}'
# OR
# cat nowcoder.txt | tr -s ' ' '
' | sort | uniq -c | sort | awk '{print $2,$1}'
原文地址:https://www.cnblogs.com/chenjo/p/14532766.html