System Administration
cancel
Showing results for 
Search instead for 
Did you mean: 

Count the number of occurances of a word

 
SOLVED
Go to solution
Simpson
Occasional Advisor

Count the number of occurances of a word

Hello,

I would like to count the number of occurances of 'foo' in a file.

If I grep for 'foo' I can wc to get the number of lines but some lines may have more than one occurance of 'foo'.

Thanks
4 REPLIES
Hein van den Heuvel
Honored Contributor
Solution

Re: Count the number of occurances of a word

I would PERL with the neat \b regular expression component for the word boundary.

Something like:

perl -ne '$hits += s/\bfoo\b/XXX/g }{ print qq($hits hits.\n)'


If you need to to this for many strings, then you can use shell substitutions, $ENV{} array entries or 'shift' to get the string values which is hard-coded as 'foo' in this example.

Change /g to /gi for case-insensitive matches.


hth,
Hein.

Peter Nikitka
Honored Contributor

Re: Count the number of occurances of a word

Hi,

it is important to know, whether really a word or a string count is wanted.
Besides this,
grep -c foo filename
is a far better line-counter than
grep foo
mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
Simpson
Occasional Advisor

Re: Count the number of occurances of a word

Thanks
Dennis Handly
Acclaimed Contributor

Re: Count the number of occurances of a word

>but some lines may have more than one occurrence of 'foo'.

If you have to have this correct, you can grep -w for foo, then use tr to break up the output, then count the lines with foo:
grep -w foo | tr -s " " "\012" | grep -c foo

Note this assumes space delimited. If you have more punctuation chars, you would have to add that to tr(1).