I have a file (search.patterns) with a list of patterns to be searched into a list of other txt files.
search.patterns
home
dog
cat
file 1.txt
home 3
tiger 4
lion 1
file 2.txt
dolphin 6
jaguar 3
dog 1
file 3.txt
donkey 3
cat 4
horse 1
so I want the first line of the pattern file to be searched in the file1, the second line searched in the file2 and the third line in file3
Output:
home 3
dog 1
cat 4
I have written some code like this:
for f in *.txt;
do
while IFS= read -r LINE;
do grep -f "$LINE" "$f" > "$f.out"
done < search.patterns
done
However, the output files are empty
Any help, highly appreciated,thanks
Best Answer
Using
bash
:Testing it:
The script saves the relevant filenames in the
files
array, and then proceeds to read patterns from thesearch.patterns
file. For each pattern, the first file in thefiles
list is queried. The processed file is then deleted from thefiles
list (yielding a new first filename in the list).If the number of patterns exceeds the number of files in
files
, there will be errors fromgrep
.