Command for counting occurrences of a word in a full file

I am trying to count the occurrences in a file.

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

The following command will give me the result, but will fail if the string contains multiple occurrences of the word

grep -c "word" filename.txt

Is there any one liner?

+3
source share
5 answers

You can use grep -oto show 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
+14
source

Set RS to awk for shorter.

awk 'END{print NR-1}' RS="word" file
+2
source
cat file | cut -d ' ' | grep -c word

, . , .

0

GNU awk :

awk -v w="word" '$1==w{n++} END{print n}' RS=' |\n' file
0
grep word filename.txt | wc -l

grepprints lines that match, then wc -lprints the number of lines matched

-1
source

All Articles