Scott Joudry
Scott Joudry

Reputation: 902

grep with multiple $

I am grepping some php code files for an array variable and I ran into an issue which I am curious to understand.

I attempted to grep:

grep -RF "$array_variable['some_key'][$key_variable]" *

and it returned nothing. However, if I escape the second dollar sign, it then finds lines with that pattern.

grep -RF "$array_variable['some_key'][\$key_variable]" *

The -F flag from the man page says it treats the pattern as a fixed string and not a regex. It seems to handle the first dollar sign only.

Please help me understand how grep is interpreting this command. Could this be a shell issue rather than a regex issue?

UPDATE Added an additional array layer, which shows why I don't want to use single quotes. It's more work to escape the single quotes than the dollar sign.

Upvotes: 2

Views: 443

Answers (2)

Luis Colorado
Luis Colorado

Reputation: 12645

I think you intend to search for occurrences of some array variable with two subindices values and you don't know that the square brackets are special for grep, meaning a class of characters. If you want to substitute the ${array_variable} name and ${key_variable} values into the grep expressión, you had better to use complete syntax as I have done, but the most important thing is that if you want to match literally the [ and ] brackets, you need to escape them. As in

grep -RF "${array_variable}\['some_key']\[${key_variable}]"

(only the left square bracket is needed to be escaped) In that case, if you have, for example foo stored in array_variable and bar in variable key_variable, the actual grep command will be

greep -RF "foo\['some_key']\[bar]"

withoug the escaping to the brackets, the regexp will search for occurences of foo, followed by one of 'somk_y and followed by one of bar, like foo'r, or foo__, but nothing similar to an array variable with its subindices.

Upvotes: 0

anubhava
anubhava

Reputation: 784898

Use single quotes instead of double quotes. Double quotes let shell expand variable names starting with $:

grep -RF '$array_variable[$key_variable]' .

For your edited question, you can use escaped $ within double quotes:

grep -RF "\$array_variable['some_key'][\$key_variable]" .

Upvotes: 2

Related Questions