写一个 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 实现吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-frequency
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
该题可以有很多种的解法, 如可以通过各种工具去解析,也可以自己用纯bash去处理。
xargs -a words.txt | xargs -n 1 | sort | uniq -c | sort -nr | awk '{print $1" "$2}'
cat words.txt | xargs -n 1 | sort | uniq -c | sort -nr | awk '{print $1" "$2}'
cat words.txt|tr -s ' ' '\n'|sort |uniq -c|sort -r|awk '{print $2,$1}'
for xargs
xargs -a file 用于从file里面去读取参数
xargs -n num 用于设置没一个命令行可以显示的参数个数
Usage: xargs [OPTION]... COMMAND [INITIAL-ARGS]...
-a, --arg-file=FILE read arguments from FILE, not standard input
-n, --max-args=MAX-ARGS use at most MAX-ARGS arguments per command line
for sort
sort 如果什么参数也不加就是单纯的对参数做排序的动做。
sort -h或者sort -n是以数字大小去做排序。
sort -r 表示的是逆序排序
同样sort -hr 或者sort -nr也是按照数字的大小去做逆序排序。
Usage: sort [OPTION]... [FILE]...
or: sort [OPTION]... --files0-from=F
-h, --human-numeric-sort compare human readable numbers (e.g., 2K 1G)
-n, --numeric-sort compare according to string numerical value
-r, --reverse reverse the result of comparisons
--sort=WORD sort according to WORD:
general-numeric -g, human-numeric -h, month -M,
numeric -n, random -R, version -V
-V, --version-sort natural sort of (version) numbers within text
for uniq
uniq -c是用于去统计相同行出现的次数
Usage: uniq [OPTION]... [INPUT [OUTPUT]]
-c, --count prefix lines by the number of occurrences
-u, --unique only print unique lines
-z, --zero-terminated line delimiter is NUL, not newline
for tr
tr ’ ’ ‘\n’就是要用\n去替换’ ‘,这样可以做到将每个以’ '做为间隔符的单词切换到每行去,这样便于排序然后做数据统计。
Usage: tr [OPTION]... SET1 [SET2]
-c, -C, --complement use the complement of SET1
-d, --delete delete characters in SET1, do not translate
-s, --squeeze-repeats replace each sequence of a repeated character
that is listed in the last specified SET,
with a single occurrence of that character
-t, --truncate-set1 first truncate SET1 to length of SET2
--help display this help and exit
--version output version information and exit
\n new line
\r return
\t horizontal tab
awk可以用于去处理数据流,它的命令行结构:
awk 'BEGIN{ print "start" } pattern { commands } END{ print "end" }' file
awk命令也可以从stdin中读取输入。
awk脚本通常由3部分组成:BEGIN、END和带模式匹配选项的公共语句块(common statement
block)。这3个部分都是可选的,可以不用出现在脚本中。
awk以逐行的形式处理文件。BEGIN之后的命令会先于公共语句块执行。对于匹配PATTERN
的行,awk会对其执行PATTERN之后的命令。最后,在处理完整个文件之后,awk会执行END之后
的命令。
awk '{print $1" "$2}'
的用意是将第一个参数和第二个参数的位置调换,用‘ ’做间隔符。