nrp
nrp

Reputation: 451

Bash: using variables in sed, double quotes cause error

I need to replace a block of code in a file using sed and variables. Here're examples which generally do not work for me:

confSearch="\"host\": \"localhost\""
confReplacement="\"host\": \"10.20.30.40\""

sed -i "s|$confSearch|$confReplacement|g" "$configFile"

However, without variable it works:

sed -i "s|\"host\": \"localhost\"|$confReplacement|g" "$configFile"

This one does search but replaces, of course, only the variable name:

sed -i 's|\"host\": \"localhost\"|$confReplacement|g' "$configFile'

Putting a variable into double or single quotes also does nothing for me. RedHat.

Would be grateful for the help.

Upvotes: 0

Views: 1711

Answers (1)

Josh Jolly
Josh Jolly

Reputation: 11796

Your first example doesn't use $confSearch - is this a typo in your question, or is this the source of the error? Your code works correctly for me:

$ cat f
"host": "localhost"
$ confSearch="\"host\": \"localhost\""
$ confReplacement="\"host\": \"10.20.30.40\""
$ sed "s|$confSearch|$confReplacement|g" f
"host": "10.20.30.40"

In order to avoid escaping so many double quotes, you could define your variables using single quotes - double quotes are not special when enclosed in single quotes.

$ confSearch='"host": "localhost"'
$ confReplace='"host": "10.20.30.40"'
$ sed "s|$confSearch|$confReplacement|g" f
"host": "10.20.30.40"

Upvotes: 2

Related Questions