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
您可以使用wc -l
您的grep
以获取包含您的关键字的行数:
grep -r "string_example" . | wc -l
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.
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?
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 match wc -l
awk
to sum the count of lines for each file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.