Mena Ortega
Mena Ortega

Reputation: 587

Recursive Grep to show only total matchin count

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.

Upvotes: 18

Views: 17491

Answers (4)

dkmike
dkmike

Reputation: 111

Just pipe to grep.

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

Upvotes: 11

Halim Qarroum
Halim Qarroum

Reputation: 14103

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.

Upvotes: 32

John Kugelman
John Kugelman

Reputation: 362187

matches=$(grep -rch "foo" /some/directory | paste -sd+ - | bc)
echo "Total matches: $matches"

The paste/bc piece sums up a list of numbers. See: Bash command to sum a column of numbers.

Upvotes: 4

btanaka
btanaka

Reputation: 382

If you only need the total, you can skip getting the count for each file, and just get a total number of matched lines:

grep -r "foo" /some/directory | wc -l

Upvotes: 2

Related Questions