[SATLUG] Command Line Warriors - Ten Cool Coreutils Commands

Mike Wallace m.a.wallace at gmail.com
Mon Feb 9 15:31:32 CST 2009

On Mon, Feb 9, 2009 at 2:21 PM, michael <michael at michaelrice.org> wrote:

> I have seen many people on the net mentioning about counting grep results
> by piping though to wc -l just an fyi grep will count its own results -c or
> --count

Grep will count its own results, but that may not be what you want it to
do.  For example, say that you want to find how many log files contain the
string "foo".  In this case, you want to count the number of files matched,
not the the number of times "foo" appeared.  To find out how many files
contain a string, you can use grep with wc:

grep -l "foo" *.log | wc -l

Also note that the -c option to grep will print out a file name and count
for each file that matches.  This may also not be what you want grep to do.
If you want a sum total of all occurrences of "foo" across multiple files,
you'd need:

cat *.log | grep -c "foo"

So the long and short of it is that "grep -c" will count for you, but only
if you're interested in counting occurrences per file.  I had the first
example in mind when I made my earlier post.  Sorry that it wasn't clear.


More information about the SATLUG mailing list