How to get no. Lines count that matches a string of all the files in a folder


Problem Description:- I have a folder which contains so many text files. I want to search for a particular string say "string_example" in all files in that folder.Then I should get the count of total no. of lines in all files which has the string "string_example". That means if there are 5 matching lines in 1st text file,10 matching lines in second text file, 3 matching lines in 3rd text file.Then the output should be 5+10+3=18

What I Have tried:- I have surfed through the internet and found some commands like

  • grep -r -n ".string_example" .

This bash command will print the file name along with line number of the lines which contains the string "string_example".Here is the sample output for better understanding

1st file:1:string_example is there

1st file:2:string_example is not there

2nd file:1:string_example is there

etc.......But the actaul output I want is 3 from the above output.

I have also tried few more bash commands but of no use.

My Question:- Is there any bash command for this kind of purpose.If not how to write a script for the following requirement.

Pls help me

You can pipe your grep with wc -l to get count of lines containing your keyword:

grep -r "string_example" . | wc -l