views:

109

answers:

2

I'm trying to find where two variables are being concatenated in a directory of scripts, but when I try the following:

grep -lire "$DATA_PATH . $AWARDS_YEAR" *

I get "undefined variable" errors...

I thought I could escape the $s by using:

grep -lire "\$DATA_PATH . \$AWARDS_YEAR" *

But I get the same error - so, how do you grep for strings with $s in?

+2  A: 

Put it in single quotes, with the escaping slash:

grep -lire '\$DATA_PATH . \$AWARDS_YEAR' *

Also note, that the dot (.) is a regex character. If you don't want it to be, escape it, too (or don't use the -e option).

Here's a nice reference with more general info.

Michael Haren
Actually, using `'\$VAR'` will produce a string with a real backslash in it in every shell I'm aware of, including tcsh, which is the default on his Freebsd system. The backslash won't prevent his grep from working but I have to think it was not intended..
DigitalRoss
I think that's what we want here--an actual backslash with an actual dollar sign to be passed as a regex
Michael Haren
Ok, if that's really what you meant. I removed the downvote. (Had to edit your answer to do it.) But remember that `$` is not magic to grep except at the end of the pattern.
DigitalRoss
@DigitalRoss- I think in this case you want `grep` to see the backslash. Otherwise `$` might gets interpreted as a metacharacter instead of a character in the text of the file.
mobrule
It's only magic at the end of a pattern...anyway it seems clear to me that the OP just wanted to prevent shell variable expansion...
DigitalRoss
+6  A: 

Tcsh is a little different about variables than the usual shells, and it's the default on FreeBSD.

So, just use single quotes, '$VAR', or escape the $ outside of the quotes: \$"VAR"

DigitalRoss
Using single quotes is the most nearly portable solution-it works across most shells on Unix-like systems. (Windows is a separate discussion.)
Jonathan Leffler
that did the trick - thanks
HorusKol