# read grep pattern from variable



## csptra (Sep 8, 2016)

Hello,

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: http://www.unix.com/shell-programming-and-scripting/44975-how-grep-variable-pattern.html

but I have a basic code structure like this:

```
#!/bin/sh

pattern="hello|help"


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

my testfile2 is this:


```
hi
hello
help
helo
h
```

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.


Thanks!


----------



## Murph (Sep 8, 2016)

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).


----------



## wblock@ (Sep 9, 2016)

Put the patterns in a file and use `egrep -f patternfile file`?


----------



## csptra (Sep 9, 2016)

Hello, 

 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


```
/path/to/file1
/path/to/file2
  etc..
```

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.


----------



## Juha Nurmela (Sep 9, 2016)

Are your patterns safe, never looking like options to egrep(1) ? _-e "$patterns"_ helps.

Juha

Be careful, some joker might create filenames with embedded newlines in them.


----------

