Home > Back-end >  count all lines containing a string in all files in a directory and see the output for each file sep
count all lines containing a string in all files in a directory and see the output for each file sep

Time:10-24

I split a file into 15 new files, each having 400 lines of text. I am trying to search each of the 15 new files for a specific string pattern but would like to know how many instances of the pattern are in each new file.

I know I can search all files in the directory using grep -r "pattern" | wc -l which gives me the overall number of lines that my pattern is in but I'd like to know which files -- I haven't been able to figure out how to do that yet

this is what I'd like it to look like:

File1 100
File2 89
File3 90

Because of how I split the files they're all titled "FILEAA" "FILEAB" "FILEAC" etc

CodePudding user response:

Just:

grep -cr "pattern" .

CodePudding user response:

Using awk:

awk '{
  count[FILENAME]  = gsub(/pattern/, "&")
}
END {
  for (filename in count) {
    print filename, count[filename]
  }
}' FILE*
  •  Tags:  
  • bash
  • Related