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
This entry is 4 of 7 in the Linux / UNIX grep Command Tutorial series. Keep reading the rest of the series:
- How To Use grep Command In Linux / UNIX
- Regular Expressions In grep
- Search Multiple Words / String Pattern Using grep Command
- Grep Count Lines If a String / Word Matches
- Grep From Files and Display the File Name
- How To Find Files by Content Under UNIX
- grep command: View Only Configuration File Directives