写一个 bash 脚本以统计一个文本文件 words.txt 中每个单词出现的频率。
为了简单起见,你可以假设:
words.txt只包括小写字母和 ' ' 。
每个单词只由小写字母组成。
单词间由一个或多个空格字符分隔。
示例:
假设 words.txt 内容如下:
the day is sunny the the
the sunny is is
你的脚本应当输出(以词频降序排列):
the 4
is 3
sunny 2
day 1
说明:
不要担心词频相同的单词的排序问题,每个单词出现的频率都是唯一的。
你可以使用一行 Unix pipes 实现吗?
方法1
# 换行
# xargs -n用于多行输出(n后面的数字:表示每行有几个字符)
☁ work cat words.txt | xargs -n1
the
day
is
sunny
the
the
the
sunny
is
is
# 扩展测试,忽略
☁ work cat words.txt | xargs -n2
the day
is sunny
the the
the sunny
is is
# 使用 sort + uniq 函数进行排列
# sort -nr 表示依照数值的大小降序排序
# uniq -c 表示在每列旁边显示该行重复出现的次数
☁ work cat words.txt | xargs -n1 | sort
day
is
is
is
sunny
sunny
the
the
the
the
☁ work cat words.txt | xargs -n1 | sort | uniq -c
1 day
3 is
2 sunny
4 the
# 使用 awk + print 函数将 1、2 列位置互换
☁ work cat words.txt | xargs -n1 | sort | uniq -c | sort -nr | awk '{print $2" "$1}'
the 4
is 3
sunny 2
day 1
最终脚本:
cat words.txt | xargs -n1 | sort | uniq -c | awk '{print $1" "$2}'
方法2
# 唯一不同的就是方法1用了xargs,方法2用了tr
# tr 命令用于转换或删除文件中的字符
# -s:缩减连续重复的字符成指定的单个字符
☁ work cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -r | awk '{ print $2, $1 }'
the 4
is 3
sunny 2
day 1
最终脚本:
cat words.txt | tr -s ' ' '\n' | sort | uniq -c | awk '{print $1" "$2}'