sachin
sachin

Reputation: 127

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

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

Upvotes: 6

Views: 20776

Answers (3)

Luca Davanzo
Luca Davanzo

Reputation: 21520

You can simply count words (-w) with wc program:

> echo "foo foo" | grep -o "foo" | wc -w
> 2

Upvotes: 0

Stenemo
Stenemo

Reputation: 619

I think that using grep -i -o string file | wc -l should give you the correct output, what happens when you do grep -i -o string file on the file?

Upvotes: 0

knite
knite

Reputation: 6171

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.

Upvotes: 9

Related Questions