題目: 192. Word Frequency
解答:
tr -s: truncate(縮短) the string with target string, but only remaining one instance (e.g. multiple whitespaces)
把多個連續的空格縮短為一個空格,即隻保留一個空格, 然後用’\n’替換空格。
cat words.txt | tr -s ' ' 多個連續的空格縮短為一個
cat words.txt | tr -s ' ' '*' 縮短後的一個空格被 ‘*’替換
uniqu -c
sort: To make the same string successive so that uniq could count the same string fully and correctly.
uniq -c: uniq is used to filter out the repeated lines which are successive, -c means counting
sort -r: -r means sorting in descending order
awk ‘{ print 2, 1 }’: To format the output, see here.
練習:
cat testfile
world
boy
hello
zero
zero
zero
alive
alive
先排序再去重,結果如下。
alive
boy
hello
world
zero
先排序再計數,結果如下
2 alive
1 boy
1 hello
1 world
3 zero