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 [OPTIONS] PATTERN [FILE...]

where:

  • OPTIONS: Any options you want to use with the command (e.g., -c to 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.

For example, to count the number of lines that contain the word “example” in a file named “file.txt”, you can use the following command:

grep -c "example" file.txt

This 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.txt

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

Leave a Comment