This is expected.
grep -r -n will perform a recursive
grep, displaying the lines which matches the given pattern, prefixed with the name of the file and the line number. It will give you every line that has a match in each file.
-n Each output line is preceded by its relative line number in the
file, starting at line 1. The line number counter is reset for
each file processed.
grep -r -c will perform a recursive
grep, displaying the filenames of all files considered, followed by the number of matches of the pattern in that file. It will give you one line for each file.
-c Only a count of selected lines is written to standard output.
To get the number of matches of a pattern in any file in a particular directory (recursively), you may feed the result of
grep -r to
wc -l as suggested in the answer that you link to:
$ grep -r 'pattern' . | wc -l
To only use
grep to achieve this:
$ grep -r 'pattern' . | grep -c 'pattern'
Although it is certainly overkill to employ a regular expression engine for this job when using
wc to count newlines is "the right tool for the job".
Note that there is also the
-o flag to
-o Print each match, but only the match, not the entire line.
This may be useful if you want to count each individual match on each line separately:
$ grep -r -o 'pattern' . | wc -l
Compare, for example, the following two
grep invocations (in
$ grep 'l' <<<"Hello world!" | wc -l
$ grep -o 'l' <<<"Hello world!" | wc -l