Alex Rivera | Logout

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

Asked 2008-12-16T12:12:56.073
344

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.)

Edit
Report

2 Answers

12

Something different than all the previous answers:

perl -lne '$count++ for m/<pattern>/g;END{print $count}' *
answered 2013-02-27T08:00:26.510
7

The AWK solution which also handles file names including colons:

grep -c string * | sed -r 's/^.*://' | awk 'BEGIN{}{x+=$1}END{print x}'

Keep in mind that this method still does not find multiple occurrences of string on the same line.

answered 2013-01-25T20:07:35.510

Your Answer