Mark Veenstra
Mark Veenstra

Reputation: 4739

Using grep -E with variables

I am trying to do a search with find and pass the results into grep. Grep has to find the files matched against string1 and string2 and string3.

I have the following command:

#/bin/bash
searchpath="/home/myfolder"
string1="abc"
string2="def"
string3="ghi"
find `echo "${searchpath}"` -type f -print0 | xargs -0 grep -l -E '"${string1}".*"${string2}".*"${string3}"'

But the result is blank, but when I do:

find /home/myfolder -type f -print0 | xargs -0 grep -l -E 'abc.*def.*ghi'

I get results. What am I doing wrong?

Upvotes: 1

Views: 807

Answers (2)

konsolebox
konsolebox

Reputation: 75478

You don't need to use command substitution. And you should use "" for quoting variables, not ':

find "${searchpath}" -type f -print0 | xargs -0 grep -l -E "${string1}.*${string2}.*${string3}"

Upvotes: 2

devnull
devnull

Reputation: 123458

Remove the single quotes from the line:

find `echo "${searchpath}"` -type f -print0 | xargs -0 grep -l -E '"${string1}".*"${string2}".*"${string3}"'

i.e., saying:

find "${searchpath}" -type f -print0 | xargs -0 grep -l -E "${string1}".*"${string2}".*"${string3}"

would work. When you surround those with single quotes, the shell is interpreting it as:

"${string1}".*"${string2}".*"${string3}"

(without expanding the variables)

Moreover, you don't need to say

`echo "${searchpath}"` 

Saying

"${searchpath}"

would suffice.

Upvotes: 3

Related Questions