Home > Blockchain >  Given an specific directory get how many occurences of an specific string appear in every file in ba
Given an specific directory get how many occurences of an specific string appear in every file in ba

Time:03-22

Given a directory get al the txt files and get how many occurences of a string are in every text file using find and grep.

find $1 -type f -name "*."$2"" -exec grep $3 -l printf {} \;

Being a $1 a directory $2 the txt format and $3 the string to find occurences.

The output must be:

$1/file1.txt
3
$1/file2.txt
6

CodePudding user response:

If you want to count the occurrences, you need to use -c or long --count flag on the grep command.

Since you also want to print the file name, you can use -printf and use the %p placeholder, which is substituted for the path of the found item.

find "$1" -type f -name "*.txt" -printf "%p\n" -exec grep -c "$2" {} \;

CodePudding user response:

Suggesting feed find results into grep command. Than format the results with awk

 grep -c "$3" $(find "$1" -name "*.$2") | awk '{print $1,$2}' FS=":" OFS="\\n"
  • Related