我正在尝试计算文件中某个单词的出现次数。
如果单词在一行中出现多次,我将计为 1。
以下命令会给我输出,但如果该行多次出现单词则会失败
grep -c "word" filename.txt
有没有一种类轮?
最佳答案
您可以使用 grep -o
来显示完全匹配,然后计算它们:
grep -o "word" filename.txt | wc -l
测试
$ cat a
hello hello how are you
hello i am fine
but
this is another hello
$ grep -c "hello" a # Normal `grep -c` fails
3
$ grep -o "hello" a
hello
hello
hello
hello
$ grep -o "hello" a | wc -l # grep -o solves it!
4
关于bash - 命令来计算整个文件中单词的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21603555/