2

I have a string, "$server['fish_stick']" (disregard double quotes)

I don't know how to successfully grep for an exact match for this string. I've tried many ways.

I've tried,

rgrep -i \$'server'\[\''fish'\_'stick'\'\] . rgrep -i "\$server\[\'fish\_stick\'\]" . rgrep -i '\$server\[\'fish\_stick\'\]' . 

Is it single quotes that are causing my issue? When I echo the first grep out it shows exactly what I want to search but returns garbage results like anything with $server in it.

Please help and explain, thank you!

2 Answers 2

1

The main problem here is that you are not quoting the argument being passed to grep. The only thing that needs to be escaped is \$ (if double quoted) and []. If you want the exact string (not using regex), just use fgrep (grep -F) which does exact string matching:

grep -F "\$server['fish_stick']" 

Works on my system:

$ foo="\$server['fish_stick']" $ echo "$foo" | grep -F "\$server['fish_stick']" $server['fish_stick'] 

Using regex:

$ echo "$foo" | grep "\$server\['fish_stick'\]" $server['fish_stick'] 

Using regex and handling nested single quotes:

$ echo "$foo" | grep '\$server\['\''fish_stick'\''\]' $server['fish_stick'] 

Inside of single quotes, nested single quotes can not be not be escaped. You have to close the quotes, and then reopen it to "escape" the single quotes.

http://mywiki.wooledge.org/Quotes

Sign up to request clarification or add additional context in comments.

Comments

0

I don't suppose you're asking how to get that string into a variable without having quoting issues. If you are, here's a way using a here-document:

str=$(cat <<'END' $foo['bar'] END ) 

To address your concern about escaping special characters for grep, you could use sed to put a backslash before any non-alphanumeric character:

grep "$(sed 's/[^[:alnum:]]/\\&/g' <<< "$str")" ... 

When used with set -x, the grep command looks like: grep '\$foo\[\'\''bar\'\''\]' ...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.