Reputation: 549
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
Upvotes: 6
Views: 26099
Reputation: 786349
You can pipe your grep
with wc -l
to get count of lines containing your keyword:
grep -r "string_example" . | wc -l
Upvotes: 14
Reputation: 25092
With this command given at the shell prompt you'll
% find -type f -name \*.h | xargs grep -l stdlib | xargs wc -l | awk '{a+=$1} END{print a}'
16372
%
.h
stdlib
and by the option -l
print only (and once) the names of the files that have at least one matchwc -l
awk
to sum the count of lines for each fileUpvotes: 0
Reputation: 74705
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.
Upvotes: 4
Reputation: 619
You want something like this?
grep -l string_example *|xargs wc -l
Edit:
You want to get numer of lines that matched in all files, or total numer of lines in files that contains matched line?
Upvotes: 2