sed Substitution Substitution Using Shell Variables

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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/"
XXllo

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

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.



Got any sed Question?