command to count occurrences of word in entire file
bash, grep, shell
Solution
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
Problem
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?