Additionally: sed expressions containing BASH variables must be double ( " ) -quoted for the variable to be interpreted correctly.
If you also double -quote your $ BASH variable (recommended practice)
- Bash Variables, Commands Affected by Numeric File and Folder Names
... then you can escape double quotes as shown in the picture:
sed -i "s/foo/bar ""$VARIABLE""/g" <file>
Those. replace the associated $ VARIABLE " with "" .
(Just -escaping "$VAR" as \"$VAR\" produces the output string " -quoted.)
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 passing 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 this 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, these variables ( ""$VAR"" ), if used in the 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!
Victoria Stuart May 09 '19 at 20:07 2019-05-09 20:07
source share