sed Substitution Using Shell Variables


Variables inside single quotes ' don't get expanded by POSIX compatible shells, so using a shell variable in a sed substitution requires the use of double quotes " instead of single quotes ':

$ var="he"
$ echo "hello" | sed "s/$var/XX/"

$ var="he"
$ echo "hello" | sed 's/$var/XX/'

Be careful of command injection when evaluating variables:

$ var='./&/;x;w/etc/passwd
> x;s/he'
$ echo "hello" | sed "s/$var/XX/"
sed: /etc/passwd: Permission denied

If the above was run as root the output would have been indistinguishable from the first example, and the contents of /etc/passwd would be destroyed.