Word Frequency Problem
#192
Description
LeetCode Problem 192.
Write a bash script to calculate the frequency of each word in a text file words.txt.
For simplicity sake, you may assume:
words.txtcontains only lowercase characters and space' 'characters.- Each word must consist of lowercase characters only.
- Words are separated by one or more whitespace characters.
Example:
Assume that words.txt has the following content:
the day is sunny the the
the sunny is is
Your script should output the following, sorted by descending frequency:
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.
- Could you write it in one-line using Unix pipes?
Solution
Approach: Pipe of standard tools
Turn the text into one word per line, then let sort and uniq -c do the counting, and finally order by count.
tr -s ' ' '\n'replaces every run of spaces with a single newline, so each word sits on its own line (the-shandles "one or more" separators).sortbrings equal words next to each other, whichuniq -cneeds, since it only collapses adjacent duplicates and prefixes each line with its count.sort -nrorders by that leading count, numerically and in descending order. Without-nthe counts would compare as text and10would come before9.awk '{print $2, $1}'swaps the columns into the requiredword countform.
Because all counts are guaranteed distinct, the unstable order of ties never matters.
# Read words.txt and print "word count" lines, most frequent first.
cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -nr | awk '{print $2, $1}'