Grep Count Lines If a String / Word Matches on Linux or Unix System
To count the number of lines in a text file that contain a specific string or word on a Linux or Unix system, you can use the grep command with the -c option.
The general syntax for the grep command is:
grep PATTERNwhere:
- OPTIONS: Any options you want to use with the command (e.g.,
-cto count the number of matching lines) - PATTERN: The string or regular expression you want to search for
- FILE: The name of the file(s) you want to search in. If no file is specified, grep will read from standard input.
grep -c "example" file.txtThis will output the number of lines that contain the word "example" in the "file.txt" file.
If you want to search for the word in multiple files, you can specify the files as additional arguments:
grep -c "example" file1.txt file2.txt file3.txtThis will output the total number of lines that contain the word "example" in all three files combined.
Note that the -c option only counts the number of lines that contain the matching string, and does not show the matching lines themselves. If you want to see the matching lines as well, you can omit the -c option.
