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. Let us see how to count lines when a match is found with the grep command.

Grep Count Lines If a String / Word Matches

The syntax is as follows on Linux or Unix-like systems:
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 indicating that word ‘vivek’ found one times:

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

Where,

  • -c : Display only a count of selected lines per FILE
  • -v : Select non-matching lines
  • --invert-match : Same as above.
Grep Count Lines If a String or Word Matches on Linux or Unix System

Using grep command to count how many times the word ‘vivek’ and ‘root’ found in /etc/passwd file on Linux or Unix.

Summing up

We can easily suppress normal grep or egrep command output bypassing the -c option. Instead, it will print a count of matching lines for each input file. I would urge you to read the grep command man page to get additional information by typing the following man command:
man grep
man egrep
grep --help
egrep --help


🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 4 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersncdu pydf
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
4 comments… add one
  • Jan Jan 9, 2013 @ 2:23

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

    Greets, Jan

  • Jan Jan 9, 2013 @ 2:24

    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 Jul 14, 2016 @ 7:51

    Can be explained better.

  • Anonymous Mar 4, 2021 @ 14:21

    I wanna count number of nameservers entry in the /etc/resolv.conf file and -c was the option that I needed. Gracias amigo.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum