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

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

🐧 Please support my work on Patreon or with a donation.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig 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
3 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre> for code samples. Problem posting comment? Email me @ webmaster@cyberciti.biz