Problem Name: 192. Word Frequency

Write a bash script to calculate the frequency (The frequency of a word x is the number of times it occurs in the text file) 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.


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


  • 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?

Code Examples

#1 Code Example with Rust Programming

Code - Rust Programming

# Read from the file words.txt and output the word frequency list to stdout.
cat words.txt| tr -s ' ' '\n' | sort | uniq -c | sort -r | awk '{print $2, $1}'
Copy The Code & Try With Live Editor


#191 Leetcode Number of 1 Bits Solution in C, C++, Java, JavaScript, Python, C# Leetcode
#193 Leetcode Valid Phone Numbers Solution in C, C++, Java, JavaScript, Python, C# Leetcode