192. Word Frequency
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.
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
From: LeetCode
Link: 192. Word Frequency
Solution:
Ideas:
- cat words.txt reads the content of words.txt.
- tr -s ' ' '\n' replaces one or more spaces with a newline character, so each word is on a new line.
- sort sorts the words alphabetically.
- uniq -c counts the occurrences of each unique word.
- sort -nr sorts the lines in numerical reverse order based on the count.
- awk '{print $2, $1}' reorders the output to show the word first and its frequency second.
Code:
bash
cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -nr | awk '{print $2, $1}'