tags:

views:

266

answers:

3

I want to use grep with two variables in a shell script

var = match

cat list.txt | while read word_from_list; do
 grep "$word_from_list" "$var" >> words_found.txt
done

But grep expects to get a file as second input:

grep: match: No such file or directory

How can this be solved?

A: 

You can use egrep (extended grep), if you want to search lines containing both words on a line you could use:

egrep "($word_from_list|$var)"

If you mean lines containing $var after $word_from_list the following might be clearer:

cat list.txt | while read word_from_list; do
 egrep "$word_from_list.*$var" >> words_found.txt
done

Come to think about it, on what text do you actually want to grep? The stdin is used for the wordlist, did you miss the filename argument to grep in your example?

rsp
+2  A: 

Two things.

  1. You need to specify the input file. Use - for standard input or supply the filename, either way it is the second parameter.
  2. After that there are a couple ways to get a boolean and via grepping. Easiest way is to change:

    grep "$word_from_list" "$var" >> words_found.txt

to:

grep "$word_from_list" - | grep "$var" >> words_found.txt

Alternatively, you can use egrep which takes in regular expressions. To get an boolean and condition you have to specify both ordering cases. The .* allows gaps between the words.

egrep "($word_from_list.*$var)|($var.*$word_from_list)" >> words_found.txt
gte525u
+1  A: 

A quick scan of the grep man page suggests that you can use -e for multiple patterns, eg.

grep -e "$word_from_list" -e "$var"

If you find yourself with a large number of patterns, you might want to use the -f option to read these from a file instead.

Hasturkun