Determining word count using grep (in cases where there are multiple words in a line)

sachin picture sachin · Oct 9, 2011 · Viewed 18.7k times · Source

Is it possible to determine the number of times a particular word appears using grep

I tried the "-c" option but this returns the number of matching lines the particular word appears in

For example if I have a file with

some words and matchingWord and matchingWord

and then another matchingWord

running grep on this file for "matchingWord" with the "-c" option will only return 2 ...

note: this is the grep command line utility on a standard unix os

Answer

knite picture knite · Oct 9, 2011

grep -o string file will return all matching occurrences of string. You can then do grep -o string file | wc -l to get the count you're looking for.