題目
描述
寫一個(gè) bash 腳本以統(tǒng)計(jì)一個(gè)文本文件 words.txt
中每個(gè)單詞出現(xiàn)的頻率抹凳。
為了簡(jiǎn)單起見,你可以假設(shè):
-
words.txt
只包括小寫字母和' '
站超。 - 每個(gè)單詞只由小寫字母組成凡傅。
- 單詞間由一個(gè)或多個(gè)空格字符分隔粪糙。
示例:
假設(shè) words.txt
內(nèi)容如下:
the day is sunny the the
the sunny is is
你的腳本應(yīng)當(dāng)輸出(以詞頻降序排列):
the 4
is 3
sunny 2
day 1
說明:
- 不要擔(dān)心詞頻相同的單詞的排序問題,每個(gè)單詞出現(xiàn)的頻率都是唯一的鸯两。
- 你可以使用一行 Unix pipes 實(shí)現(xiàn)嗎闷旧?
解答
思路
cat
讀取,tr
排重钧唐,sort
排序以支持uniq
忙灼,uniq
統(tǒng)計(jì),sort
逆序钝侠,awk
顯示
代碼
cat words.txt | tr -s '[:blank:]' '\n' | sort | uniq -c | sort -r | awk '{print$2,$1}'