Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Grep to show only total matchin count

Tags:

grep

bash

shell

I'm trying to do a recursive grep search such as:

grep -r -c "foo" /some/directory

which give me output auch as:

/some/directory/somefile_2013-04-08.txt:0
/some/directory/somefile_2013-04-09.txt:1
/some/directory/somefile_2013-04-10.txt:4
...etc

however, I would like to just get the total number of matches in all files, like:

Total matches:    5

I've played around with some other examples such as in this thread, although I can't seem to do what should be so simple.

like image 289
Mena Ortega Avatar asked Apr 21 '13 00:04

Mena Ortega


People also ask

How do you count the number of matches in grep?

Counting Matches With grepThe grep command has the -c flag, which will count the number of lines matched and print out a number. This is useful for lots of things, such as searching through log files for the number of entries from a particle IP, endpoint, or other identifier.

Does grep work recursively?

To recursively search for a pattern, invoke grep with the -r option (or --recursive ). When this option is used grep will search through all files in the specified directory, skipping the symlinks that are encountered recursively.

What is recursive search in grep?

From man grep. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option.

How do I get my first grep match?

-m 1 means return the first match in any given file. But it will still continue to search in other files. Also, if there are two or more matched in the same line, all of them will be displayed.


2 Answers

grep -ro "foo" /some/directory | wc -l | xargs echo "Total matches :"

The -o option of grep prints all the existing occurences of a string in a file.

like image 60
Halim Qarroum Avatar answered Sep 29 '22 11:09

Halim Qarroum


Just pipe to grep.

grep -r "foo" /some/directory | grep -c "foo"
like image 30
dkmike Avatar answered Sep 29 '22 13:09

dkmike