Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

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

like image 215
Željko Filipin Avatar asked Dec 16 '08 12:12

Željko Filipin


People also ask

How do I grep multiple files?

To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.

How do you use grep and wc?

Combining wc With grepIn conjunction with grep, wc gives a count of occurrences in a set of files. For example, let's say we need to figure out how many errors of a certain type occurred over several log files. grep sends all the results to standard input, and wc performs a line count of that input.


2 Answers

This works for multiple occurrences per line:

grep -o string * | wc -l 
like image 151
Jeremy Lavine Avatar answered Oct 03 '22 01:10

Jeremy Lavine


cat * | grep -c string 
like image 41
Bombe Avatar answered Oct 03 '22 02:10

Bombe