Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

command to count occurrences of word in entire file

Tags:

grep

bash

shell

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?

like image 297
hardy_sandy Avatar asked Nov 29 '22 01:11

hardy_sandy


1 Answers

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
like image 88
fedorqui 'SO stop harming' Avatar answered Dec 04 '22 04:12

fedorqui 'SO stop harming'