Count all occurrences of a string in lots of files with grep

Željko Filipin picture Željko Filipin · Dec 16, 2008 · Viewed 391k times · Source

I have a bunch of log files. I need to find out how many times a string occurs in all files.

grep -c string *

returns

...
file1:1
file2:0
file3:0
...

Using a pipe I was able to get only files that have one or more occurrences:

grep -c string * | grep -v :0

...
file4:5
file5:1
file6:2
...

How can I get only the combined count? (If it returns file4:5, file5:1, file6:2, I want to get back 8.)

Answer

Jeremy Lavine picture Jeremy Lavine · Jul 14, 2010

This works for multiple occurrences per line:

grep -o string * | wc -l