sed: Delimiter Issues


When doing variable substitution with sed things break if the value contains the delimiter used by sed.

For example:

MY_VAR="This works"
echo "My value is MY_VALUE" | sed "s/MY_VALUE/$MY_VAR/g"

MY_VAR="This/breaks"
echo "My value is MY_VALUE" | sed "s/MY_VALUE/$MY_VAR/g"

Solution: Known Input

If the input is well understood you can just change the delimiter used to resolve the issue:

MY_VAR="This still works"
echo "My value is MY_VALUE" | sed "s|MY_VALUE|$MY_VAR|g"

MY_VAR="This/now/works"
echo "My value is MY_VALUE" | sed "s|MY_VALUE|$MY_VAR|g"

In this example I used | but you can basically use any character, as long as it is not part of the strings being operated on.

Solution: Unknown Input

If the input is completely unknowable it might be best just to escape the control character used by sed in the input.

MY_VAR="This still works"
MY_VAR=$(echo ${MY_VAR} | sed -e "s#/#\\\/#g")
echo "My value is MY_VALUE" | sed "s/MY_VALUE/$MY_VAR/g"

MY_VAR="This/now/works"
MY_VAR=$(echo ${MY_VAR} | sed -e "s#/#\\\/#g")
echo "My value is MY_VALUE" | sed "s/MY_VALUE/$MY_VAR/g"
sed