在linux bourne shell中:如何计算文件中特定单词的出现次数

use*_*473 3 unix shell awk grep

通过语言,我的意思是任何以空格分隔的字符串.

假设文件test.txt具有由空格分隔的以下单词:

hello hello hello hell osd
hello
hello 
hello
hellojames beroo helloooohellool axnber hello
way
how 
Run Code Online (Sandbox Code Playgroud)

我想计算每行中出现单词hello的次数.

我使用该命令awk -F "hello" '{print NF-1}' test.txt显示每行中单词hello的出现次数:

3
1
1
1
4
0
0
Run Code Online (Sandbox Code Playgroud)

因此它总共发现了3 + 1 + 1 + 1 + 4 = 10次.

问题是在第四行:你好只发生一次作为一个单独的单词; 词如hellojameshelloooohellool不应计入因为不是由空格分隔.

所以我希望它找到7次出现的hello作为一个单独的单词.

你能帮我写一个返回正确总共7次的命令吗?

Kev*_*vin 6

awk '{ for(i=1; i<=NF; i++) if($i=="hello") c++ } END{ print c }' file.txt
Run Code Online (Sandbox Code Playgroud)

如果您需要它来打印每一行:

awk '{ c=1; for(i=0; i<=NF; i++) if($i=="hello") c++; print c }'
Run Code Online (Sandbox Code Playgroud)