Grep Count Lines If a String / Word Matches

Posted on in Categories last updated February 18, 2011

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

3 comment

Leave a Comment