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.
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.
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.
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.
-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.
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.
Just pipe to grep.
grep -r "foo" /some/directory | grep -c "foo"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With