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

Posted on in Categories , , last updated May 3, 2017

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.


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
$ grep -w -c vivek /etc/passwd
Sample outputs:


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


Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

3 comment

Leave a Comment