read grep pattern from variable


I'm sure this is easy, but trying to figure this out: I see a similar example here: but can't get it to work:

but I have a basic code structure like this:


while read line;do
  egrep $pattern $line
done < testfile2

my testfile2 is this:


I keep getting the following error no matter if I single quote or double quote. or use various brackets (which get me other errors)

egrep: hi: No such file or directory
egrep: hello: No such file or directory
egrep: help: No such file or directory
egrep: helo: No such file or directory
egrep: h: No such file or directory

I'm sure its simple and I'm overlooking something, but hoping someone can provide help or another document.

Um, you could just do egrep "$pattern" testfile2, since that's what (e)grep does and it does not really make sense to re-implement simply iterating over the lines in the input stream.

If you really want to be complicated and inefficient, you need echo "$line" | egrep "$pattern". It is always good practice to wrap your variables in quotes, to prevent them being split over multiple command arguments ( argv[] in C terms).

I apologize, I didn't mention my over all goal, I want to read line by line through a file containing absolute paths for a returned list of files. so the while read line looks something like (for my real case, I posted my test case)

while read line;do
   grep <pattern> $line
   done < testfile2

where testfile2 actually contains


and I want to use the pattern against file1 & file2. It works fine if I don't put the pattern in a variable. but I would like to store the pattern in a variable to store at the top of my code.
I don't want to run pattern against testfile2 (in my real case) but the files contained in the testfile2. (the file list is the output of another search) I supposed I could combine them, but, at this point, I want to keep them separate.

Thanks for the suggestion wblock, but would rather cut down on wblock. I suppose I could create / remove the file dynamically. That would be a good idea. But was hoping to get the variable to work.

I apologize I didn't post my real case and just my test case I was working on.