command to count occurrences of word in entire file

无人久伴 提交于 2020-05-29 08:15:46

问题


I am trying to count the occurrences of a word in a file.

If word occurs multiple times in a line, I will count is a 1.

Following command will give me the output but will fail if line has multiple occurrences of word

grep -c "word" filename.txt

Is there any one liner?


回答1:


You can use grep -o to show the exact matches and then count them:

grep -o "word" filename.txt | wc -l

Test

$ 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



回答2:


Set RS in awk for a shorter one.

awk 'END{print NR-1}' RS="word" file



回答3:


GNU awk allows it to be done in single command with use of multiple piped commands:

awk -v w="word" '$1==w{n++} END{print n}' RS=' |\n' file



回答4:


cat file | cut -d ' ' | grep -c word

This assumes that all words in the file have spaces between the words. If there's punctuation concatenating the word to itself, or otherwise no spaces on a single line between the word and itself, they'll count as one.




回答5:


grep word filename.txt | wc -l

grep prints the lines that match, then wc -l prints the number of lines matched



来源:https://stackoverflow.com/questions/21603555/command-to-count-occurrences-of-word-in-entire-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!