18

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.

2 Answers 2

21

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" filename | wc -l
1
  • 1
    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". Commented Jun 21, 2016 at 19:59
2

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.

2
  • 1
    worked perfectly, but if you're still around, would you mind making it better by explaining step by step what was done there? Commented Jun 12, 2020 at 15:31
  • For grep: -r searches recursively, -Z prints out the output with the filename separated from the number of matching lines with the nul character. For awk: -F '\0' makes the field delimiter the nul character. s+=$NF is the sum of the values of the last field - NF is the number of fields $NF is therefore the last field, and then s is printed when awk runs out of input and the program ends.
    – cbz
    Commented Feb 28, 2022 at 23:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .