繁体   English   中英

如何计算一个单词在目录的所有文件中出现的次数?

[英]How to count occurrences of a word in all the files of a directory?

我正在尝试计算整个目录中出现的特定单词。 这可能吗?

例如,有一个包含 100 个文件的目录,所有这些文件中都可能包含单词“aaa”。 我如何计算该目录下所有文件中“aaa”的数量?

我试过类似的东西:

 zegrep "xception" `find . -name '*auth*application*' | wc -l 

但它不起作用。

grep -roh aaa. | wc -w

Grep 递归搜索当前目录中的所有文件和目录 aaa,而 output 仅匹配,而不是整行。 然后,只需使用wc来计算有多少单词。

另一种基于findgrep的解决方案。

find . -type f -exec grep -o aaa {} \; | wc -l

应该正确处理带有空格的文件名。

让我们使用 AWK!

$ function wordfrequency() { awk 'BEGIN { FS="[^a-zA-Z]+" } { for (i=1; i<=NF; i++) { word = tolower($i); words[word]++ } } END { for (w in words) printf("%3d %s\n", words[w], w) } ' | sort -rn; }
$ cat your_file.txt | wordfrequency

这列出了每个单词在提供的文件中出现的频率。 如果你想查看你的单词出现的次数,你可以这样做:

$ cat your_file.txt | wordfrequency | grep yourword

要在目录中的所有文件中查找单词的出现(非递归),您可以执行以下操作:

$ cat * | wordfrequency | grep yourword

要在目录(及其子目录)中的所有文件中查找您的单词的出现,您可以执行以下操作:

$ find . -type f | xargs cat | wordfrequency | grep yourword

来源: AWK-ward Ruby

以最简单的方式使用grep 尝试grep --help了解更多信息。


  1. 要计算特定文件中的单词数:

     grep -c <word> <file_name>

    例子:

     grep -c 'aaa' abc_report.csv

    Output:

     445

  1. 要计算整个目录中的一个单词:

     grep -c -R <word>

    例子:

     grep -c -R 'aaa'

    Output:

     abc_report.csv:445 lmn_report.csv:129 pqr_report.csv:445 my_folder/xyz_report.csv:408
find .|xargs perl -p -e 's/ /\n'|xargs grep aaa|wc -l

将文件和 grep 和 output 放在一起: cat $(find /usr/share/doc/ -name '*.txt') | zegrep -ic '\<exception\>' cat $(find /usr/share/doc/ -name '*.txt') | zegrep -ic '\<exception\>'

如果您想匹配 'exceptional',请不要在单词周围使用 '\<' 和 '\>'。

如何开始:

cat * | sed 's/ /\n/g' | grep '^aaa$' | wc -l

如以下成绩单:

pax$ cat file1
this is a file number 1

pax$ cat file2
And this file is file number 2,
a slightly larger file

pax$ cat file[12] | sed 's/ /\n/g' | grep 'file$' | wc -l
4

sed将空格转换为换行符(您可能还希望包含其他空格字符,例如制表符,使用sed 's/[ \t]/\n/g' )。 grep只是获取那些具有所需单词的行,然后wc会为您计算这些行。

现在可能存在此脚本不起作用的边缘情况,但对于绝大多数情况应该没问题。

如果你想要一整棵树(不仅仅是一个目录级别),你可以使用类似的东西:

( find . -name '*.txt' -exec cat {} ';' ) | sed 's/ /\n/g' | grep '^aaa$' | wc -l

还有一个 grep 正则表达式语法仅用于匹配单词:

# based on Carlos Campderrós solution posted in this thread
man grep | less -p '\<'
grep -roh '\<aaa\>' . | wc -l

有关匹配正则表达式语法的不同单词,请参见:

man re_format | less -p '\[\[:<:\]\]'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM