Grep Count Lines If a String / Word Matches

by on February 18, 2010 · 2 comments· LAST UPDATED February 18, 2011

in

How do I count lines if given word or string matches for each input file under Linux or UNIX operating systems?

You need to pass the -c or --count option to suppress normal output. It will display a count of matching lines for each input file:
$ grep -c vivek /etc/passwd
OR
$ grep -w -c vivek /etc/passwd
Sample outputs:

1

However, with the -v or --invert-match option it will count non-matching lines, enter:
$ grep -c vivek /etc/passwd
Sample outputs:

45
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 2 comments… read them below or add one }

1 Jan January 9, 2013 at 2:23 am

dude, typo again:
instead of
grep -c vivek /etc/passwd
it must be, as correctly described
grep -v vivek /etc/passwd

Greets, Jan

Reply

2 Jan January 9, 2013 at 2:24 am

dude, typo again:
instead of
grep -c vivek /etc/passwd
it must be, as correctly described
grep -c -v vivek /etc/passwd
:)
Greets, Jan

Reply

Leave a Comment

Tagged as: , , , , , , , ,

Previous Faq:

Next Faq: