获取所有单词的文本文件单词出现计数并排序打印输出

33 sort

我有一个命令可以处理一个文本文件,计算所有出现的单词并像这样打印出来:

user@box $˜ magic-command-i-forgot | with grep | and awk | sort ./textfile.txt
66: the
54: and
32: I
16: unix
12: bash
5:  internet
3:  sh
1: GNU/Linux
Run Code Online (Sandbox Code Playgroud)

因此,它不是逐行搜索,而是逐词搜索,而且它会搜索所有单词,而不仅仅是 1 个单词。很久以前我在互联网上的某个地方找到了它,但我找不到或不记得它了。

sel*_*ler 40

我会使用tr而不是awk

echo "Lorem ipsum dolor sit sit amet et cetera." | tr '[:space:]' '[\n*]' | grep -v "^\s*$" | sort | uniq -c | sort -bnr
Run Code Online (Sandbox Code Playgroud)
  • tr 只是用换行符替换空格
  • grep -v "^\s*$" 修剪空行
  • sort 准备作为输入 uniq
  • uniq -c 计算出现次数
  • sort -bnr 以数字逆序排序,同时忽略空格

哇。结果证明这是一个很好的命令来计算每行发誓

找 。-name "*.py" -exec cat {} \; | tr '[:space:]' '[\n*]' | grep -v "^\s*$" | 排序 | uniq -c | 排序-bnr | 他妈的


Gil*_*il' 8

  1. 将输入拆分为单词,每行一个。
  2. 对生成的单词(行)列表进行排序。
  3. 挤压多次出现。
  4. 按出现次数排序。

要将输入拆分为单词,请将您认为是单词分隔符的任何字符替换为换行符。

<input_file \
tr -sc '[:alpha:]' '[\n*]' | # Add digits, -, ', ... if you consider
                             # them word constituents
sort |
uniq -c |
sort -nr
Run Code Online (Sandbox Code Playgroud)


Bra*_*ram 5

不使用 grep 和 awk 但这似乎可以满足您的需求:

for w in `cat maxwell.txt`; do echo $w; done|sort|uniq -c
  2 a
  1 A
  1 an
  1 command
  1 considered
  1 domain-specific
  1 for
  1 interpreter,
  2 is
  1 language.
  1 line
  1 of
Run Code Online (Sandbox Code Playgroud)


Pri*_*ley 5

使用awk/sort/uniq解决方案:

awk '{for(w=1;w<=NF;w++) print $w}' ~/textFile.txt | sort | uniq -c | sort -nr
Run Code Online (Sandbox Code Playgroud)