用于计算文件中Word出现次数的Shell脚本

Man*_*san 4 shell

让我们以下面的内容为例

    This file is a test file 
    this file is used to count the word 'file' in this test file
    there are multiple occurrences of word file in some lines in this test file
Run Code Online (Sandbox Code Playgroud)

我想在上面的内容中计算"文件"这个词.

我正在使用下面的shell命令

   cat $filename |  sed "s/_/new/g" | sed "s/$word/_/g" | tr -c -d _ |wc -c
Run Code Online (Sandbox Code Playgroud)

那还好还是有更好的想法..?

Nib*_*ler 9

使用tr分隔单词然后grep和wc似乎是可能的:

tr -s ' ' '\n' < file.txt | grep file | wc -l
Run Code Online (Sandbox Code Playgroud)


Nyk*_*kin 6

grep $word $filename -o | wc -l
Run Code Online (Sandbox Code Playgroud)


tri*_*eee 5

grep -cow "$word" "$filename"
Run Code Online (Sandbox Code Playgroud)

-c选项指定报告计数.

-o选项指定计算每次出现的次数,而不仅仅是匹配行的数量.

-w选项指定仅计算单词匹配,即不是部分匹配,例如"文件"或"配置文件".

不幸的是,一些版本grep不正确当你把工作-c-o.如果您有这个错误,@ Nykakin的答案是一个很好的解决方法.

同时注意插值变量的正确引用.