How to get no. the number of lines that matches a line from all files in the folder
Description of the problem: - I have a folder containing so many text files. I want to search for a specific string, say "string_example" in all files in that folder. Then I will need to calculate the total. lines in all files with the string "string_example". This means if there are 5 matching lines in the 1st text file, 10 matching lines in the second text file, 3 matching lines in the 3rd text file. Then the output should be 5 + 10 + 3 = 18
What I tried: - I was surfing the internet and found a few commands like
-
grep -r -n ".string_example" .
This bash command will print the filename along with the line number of the lines that contains the string "string_example". Here is a sample output for better understanding
1st file: 1: string_example is
1st file: 2: string_example does not exist
Second file: 1: string_example is
etc. But the actaul output I want is 3 from the above output.
I've also tried several bash commands but haven't used.
My question is : - Is there any bash command for this kind of purpose. Unless you write a script for the following requirement.
Help me help
source to share
With this command given on the shell command line, you will
% find -type f -name \*.h | xargs grep -l stdlib | xargs wc -l | awk '{a+=$1} END{print a}'
16372
%
- get a list of all files here and further, ending with
.h
- grep these files to find links to
stdlib
and optionally-l
print only (and once) filenames that have at least one match - pass a list of names
wc -l
- use
awk
to sum the number of lines for each file
source to share