I want to know how many instances of a pattern are found by grep while looking recursively through a directory structure. It seems I should be able to pipe the output of grep through something which would count the lines.


I was able to put the answer together with help from this question. The program "wc" program counts newlines, words and byte counts. The "-l" option specifies that the number of lines is desired. For my application, the following worked nicely to count the number of instances of "somePattern":

$grep -r "somePattern" | wc -l
  • There's also grep -c, but it doesn't exactly do what you require: "Suppress normal output; instead print a count of matching lines for each input file". – Martin von Wittich Jun 21 '16 at 19:59

At least with GNU tools:

grep -rcZ "some_pattern" | awk -F'\0' '{s+=$NF}END{print s}'

This is likely superior in speed compared to wc -l.

It also works for files with newline in name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.