≡ 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
Share this tutorial on:
{ 3 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

  • Yash July 14, 2016, 7:51 am

    Can be explained better.

Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">


   Tagged with: , , , , , , , ,