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 grep
:
-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 bash
or ksh93
):
$ grep 'l' <<<"Hello world!" | wc -l
1
$ grep -o 'l' <<<"Hello world!" | wc -l
3
-c
option should work: it lists every input file and append the numer of matches (or 0) right after the file name. Checkgrep
manpage for more details. I honestly don't know if there's some kind of 'grand total' option available.