❤ ️ the original ❤ ️
Write a bash script to count the frequency of each word in a text file called words.txt.
For the sake of simplicity, you can assume:
words.txt
Only lowercase letters and' '
。- Each word consists of lowercase letters only.
- Words are separated by one or more space characters.
Example:
Assume that the contents of words.txt are as follows:
the day is sunny the the
the sunny is is
Copy the code
Your script should output (in descending order of word frequency) :
the 4
is 3
sunny 2
day 1
Copy the code
Description:
- Don’t worry about sorting words with the same frequency. Each word has a unique frequency.
- You can use one line
Unix pipes
To achieve?
⭐️ ⭐️
Note a few key words: word frequency descending order, counting the number of occurrences of each word, using a command line.
Using xargs to display all rows in a single column:
cat words.txt | xargs -n1
Copy the code
(2) usesort + uniq
Functions are arranged:
sort -nr
Sort values in descending order by size.uniq -c
Displays the number of times a row has been repeated next to each column.
cat words.txt | xargs -n1 | sort | uniq -c | sort -nr
Copy the code
(3) usingawk + print
Function () swap columns 1 and 2:
cat words.txt | xargs -n 1 | sort | uniq -c | sort -nr | awk '{print $2" "$1}'
Copy the code
So far, the problem is solved.
Go to LeetCode and check out the results:
❄️ at the end ❄️
Xargs, sort, uniq, awk
That’s the end of this sharing
If you think the article is helpful to you, like, collect, follow, comment, one key four support, your support is the biggest motivation for my creation.