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

https:‮//‬www.lautturi.com
Grep Count Lines If a String / Word Matches on Linux or Unix System

To count the number of lines that contain a string or word using the grep command in Unix or Linux, you can use the -c or --count option.

For example, to count the number of lines in a file that contain the word "test," you can use the following command:

grep -c "test" file.txt

This will print the number of lines in the file file.txt that contain the word "test."

You can also use the -o or --only-matching option to print only the matching lines, and pipe the output to the wc command with the -l option to count the number of lines:

grep -o "test" file.txt | wc -l

This will also count the number of lines in the file file.txt that contain the word "test."

Created Time:2017-10-28 20:40:39  Author:lautturi