15

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.

Community
  • 1
  • 1
Mena Ortega
  • 457
  • 2
  • 5
  • 7

4 Answers4

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

Halim Qarroum
  • 13,985
  • 4
  • 46
  • 71
  • 1
    thanks, useful command. i'm not sure which is accurate though, since with your example i get 447 matches, and Johns I get 392. I'll have to play with it a bit more to know I guess. – Mena Ortega Apr 21 '13 at 00:56
  • This command has perfectly worked for me anyway. I've updated my example to add a string giving you the result when the command ends. – Halim Qarroum Apr 21 '13 at 01:01
  • 1
    Multiple matches within a single line each produce a separate line of output with `-o`. – chepner Apr 21 '13 at 02:28
10

Just pipe to grep.

grep -r "foo" /some/directory | grep -c "foo"
dkmike
  • 101
  • 1
  • 3
4
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.

Community
  • 1
  • 1
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • wow. awesome command :) - is difficult to add "Total matches: " to it? – Mena Ortega Apr 21 '13 at 00:49
  • I ended up going with Halims, because it combined everything in one line. I'll definitely keep this one handy though, as it could be quite useful. ty again. – Mena Ortega Apr 21 '13 at 02:56
2

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
btanaka
  • 382
  • 2
  • 6
  • This will only print each line where one or many occurences have been found. This will not return all the existing occurences of a string or pattern. – Halim Qarroum Apr 21 '13 at 00:52