Grep Count Lines If a String / Word Matches on Linux or Unix System

last updated in Categories , ,

How do I count lines if given word or string matches for each input file under Linux or UNIX-like 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.

Syntax

The syntax is:
grep -c 'word-to-search' fileNameHere
For example, search a word named ‘vivek’ in /etc/passwd and count line if a word matches:
$ 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 -v -c vivek /etc/passwd
Sample outputs:

45

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Share this on (or read 3 comments/add one below):

3 comment

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

    Greets, Jan

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

    Have a question? Post it on our forum!