bash 词频统计

写一个 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:
sort -n 将字符串转数字
sort -r 指定顺序为从大到小
sort -k 2 指定第二个字段作为排序判断标准

 sort -rnk 1  (r表示逆向排序, n表示按数值排序, k表示按第k列进行排序)

sort | uniq -c 通常一起用来统计重复出现的次数。

uniq可检查文本文件中重复出现的行列, -c或--count 在每列旁边显示该行重复出现的次数。

cat:

cat m1 (在屏幕上显示文件ml的内容)

cat m1 m2 (同时显示文件ml和m2的内容)

cat m1 m2 > file (将文件ml和m2合并后放入文件file中)

tr -s:  -s, --squeeze-repeats  

replace each input sequence of a repeated character                            

that is listed in SET1 with a single occurrence                            

of that character

tr -s ' ' '\n'可实现把空格替换为换行符的分割操作

答案:

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

猜你喜欢

转载自my.oschina.net/lfxu/blog/1818874