leetcode-175-Combine-Two-Tables

描述


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:

1
2
the day is sunny the the
the sunny is is

Your script should output the following, sorted by descending frequency:

1
2
3
4
the 4
is 3
sunny 2
day 1

Note:

Don’t worry about handling ties, it is guaranteed that each word’s frequency count is unique.

解决方案


这种需求是有很多方法解决的,但思路大致都一样:去重,排序,格式化输出。不得不说,类 Unix 系统的管道真是一个伟大的想法:)

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

先通过 cat 命令得到 words.txt 文件的内容,利用 tr 命令将空格符合替换成换行符,进行一次排序,这样就可以通过 uniq 命令统计重复行出现的次数,再排序一次,通过 -r 参数获得一个倒叙的排序,再通过 awk 命令格式化输出。

题目来源