views:

30

answers:

2

Let's say that I want to count the number of "o" characters in the text

oooasdfa
oasoasgo

My first thought was to do grep -c o, but this returns 2, because grep returns the number of matching lines, not the total number of matches. Is there a flag I can use with grep to change this? Or perhaps I should be using awk, or some other command?

+5  A: 

This will print the number of matches:

echo "oooasdfa
oasoasgo" | grep -o o | wc -l
ngoozeff
Was just getting ready to put that, the grep -o parameter displays each match instead of the matching line. However you cannot use -c and -o together to count the characters, you must pipe it to wc.
Brandon Horsley
A: 

you can use the shell (bash)

$ var=$(<file)
$ echo $var
oooasdfa oasoasgo
$ o="${var//[^o]/}"
$ echo ${#o}
6

awk

$ awk '{m=gsub("o","");sum+=m}END{print sum}' file
6
ghostdog74