Search code examples
shellgrepksh

grep in a directory for the set of search patterns saved in a file


I want to grep for multiple search patterns. I cannot use grep -E or egrep with '|' separated search patterns as they are huge in number. I have stored these patterns in a file. How can run grep on a directory to give me list of files whose content matches with the search pattern

Detailed Scenario:

I have 2 directories

A1 - 100 files

B1 - 100 files, each file has just a single line ->filename present in A1.

Given 10 random files from A1, i want to know which B1 files has those names. I could run grep -E "A1file1|A1file2|A1file3...and so on |A1file10" * in the B1 directory and it will give me list of those 10 files. But when the number of files increase lets say 100 or 1000 then its not feasible to write the command. So i have stored the searchpattern(i.e. filenames to be grepped in B1) in a file. How can i grep in B1 using searchpatterns saved in a file?


Solution

  • With an awk that supports nextfile, e.g. GNU awk, and assuming searchpattern is just a file of newline-separated file names and B1 doesn't contain more files than can fit in a shell command arguments list:

    awk '
        NR==FNR { names[$0]; next }
        FILENAME in names { print FILENAME }
        { nextfile }
    ' searchpattern B1/*