≡ Menu

Grep Count Lines If a String / Word Matches

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
Tweet itFacebook itGoogle+ itPDF itFound an error/typo on this page?

{ 2 comments… add one }

  • Jan January 9, 2013, 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

  • Jan January 9, 2013, 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

Leave a Comment