Aside: sed expressions containing BASH variables need to be double ("
)-quoted for the variable to be interpreted correctly.
If you also double-quote your $BASH variable (recommended practice)
... then you can escape the variable double quotes as shown:
sed -i "s/foo/bar ""$VARIABLE""/g" <file>
I.e., replace the $VARIABLE-associated "
with ""
.
(Simply -escaping "$VAR"
as \"$VAR\"
results in a "
-quoted output string.)
Examples
$ VAR='apples and bananas'
$ echo $VAR
apples and bananas
$ echo "$VAR"
apples and bananas
$ printf 'I like %s!\n' $VAR
I like apples!
I like and!
I like bananas!
$ printf 'I like %s!\n' "$VAR"
I like apples and bananas!
Here, $VAR is "
-quoted before piping to sed (sed is either '
- or "
-quoted):
$ printf 'I like %s!\n' "$VAR" | sed 's/$VAR/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed 's/"$VAR"/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed 's/$VAR/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed 's/""$VAR""/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed "s/$VAR/cherries/g"
I like cherries!
$ printf 'I like %s!\n' "$VAR" | sed "s/""$VAR""/cherries/g"
I like cherries!
Compare that to:
$ printf 'I like %s!\n' $VAR | sed "s/$VAR/cherries/g"
I like apples!
I like and!
I like bananas!
$ printf 'I like %s!\n' $VAR | sed "s/""$VAR""/cherries/g"
I like apples!
I like and!
I like bananas!
... and so on ...
Conclusion
My recommendation, as standard practice, is to
"
-quote BASH variables ("$VAR"
)"
-quote, again, those variables (""$VAR""
) if they are used in a sed expression (which itself must be "
-quoted, not '
-quoted)$ VAR='apples and bananas'
$ echo "$VAR"
apples and bananas
$ printf 'I like %s!\n' "$VAR" | sed "s/""$VAR""/cherries/g"
I like cherries!