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.

ADVERTISEMENTS

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
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 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 VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
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.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.