Linux Grep – How to Grep Pairs of Patterns and File

greplinux

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:

#!/bin/bash

files=( 'file 1.txt' 'file 2.txt' 'file 3.txt' )

while IFS= read -r pattern; do
    grep -e "$pattern" "${files[0]}"
    files=( "${files[@]:1}" )
done <search.patterns

Testing it:

$ bash script.sh
home 3
dog 1
cat 4

The script saves the relevant filenames in the files array, and then proceeds to read patterns from the search.patterns file. For each pattern, the first file in the files list is queried. The processed file is then deleted from the files 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 from grep.

Related Question