Write a bash script to calculate the frequency of each word in a text file words.txt
.bash
For simplicity sake, you may assume:spa
words.txt
contains only lowercase characters and space ' '
characters.
For example, assume that words.txt
has the following content:code
the day is sunny the the the sunny is is
Your script should output the following, sorted by descending frequency:blog
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.排序
cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -r | awk '{print $2" "$1}' tr -s: 使用指定字符串替換出現一次或者連續出現的目標字符串(把一個或多個連續空格用換行符代替) sort: 將單詞從小到大排序 uniq -c: uniq用來對連續出現的行去重,-c參數爲計數 sort -r: -r 倒序排列 awk '{ print $2, $1 }': 格式化輸出,將每一行的內容用空格分隔成若干部分,$i爲第i個部分。