tags:

views:

5939

answers:

4

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

grep -c string *

retruns

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

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

grep -c string * | grep -v :0

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

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

+1  A: 

Instead of using -c, just pipe it to wc -l.

grep string * | wc -l

This will list each occurrence on a single line and then count the number of lines.

This will miss instances where the string occurs 2+ times on one line, though.

Michael Haren
+4  A: 
cat * | grep -c string
Bombe
you where 52 seconds faster than me ;-)
Joachim Sauer
This has the same limitation that it counts multiple occurrences on one line only once. I am guessing that this behavior is OK in this case, though.
Michael Haren
Thanks! That did the trick.
Željko Filipin
@Michael Haren Yes, there could be only one occurrence of string in a line.
Željko Filipin
+1  A: 
cat * | grep -c string

One of the rare useful applications of cat.

Joachim Sauer
+1  A: 

This works for multiple occurrences per line:

grep -o string * | wc -l
Jeremy Lavine