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

+3


source to share


4 answers


You can pass yours grep

with wc -l

to get the number of lines containing your keyword:



grep -r "string_example" . | wc -l

      

+6


source


You can also use awk for this:

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

      



c

is incremented every time the string matches the pattern. After all files have been read, print the total score.

+3


source


Do you need something like this?

grep -l string_example *|xargs wc -l

      

Edit:
Do you want to get the number of lines that match in all files, or the total number of lines in files that contain the matching line?

+2


source


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
0


source







All Articles