Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

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

like image 369
Sudhir kumar Avatar asked Oct 25 '14 10:10

Sudhir kumar


2 Answers

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

grep -r "string_example" . | wc -l
like image 63
anubhava Avatar answered Oct 04 '22 02:10

anubhava


You could also use awk to do this:

awk '/string_example/{++c}END{print c}' *

c is incremented every time a line matches the pattern. Once all files have been read, print the total count.

like image 30
Tom Fenech Avatar answered Oct 04 '22 02:10

Tom Fenech