I have a sed script where the replacement string comes from user input, e.g.
echo -n "Enter identity? "
read identity
sed -i "s:^export identity=.*:export identity='$identity':g" $CFG_FILE
The problem is that the user may enter a value that has special meaning to sed, for example:
abc:abc
In this case, the colon character used in the sed statement, so causes an error.
Is there a way to allow the user to enter any value, but if a value has special meaning to sed then it gets escaped?
Note this question is similar to, but different from: https://stackoverflow.com/questions/23186445/escape-replacement-string-from-bash-source-file
Since you are using the variable in the replacement, you need to escape the character that represents the delimiter. Use shell parameter expansion:
This would transform
abc:abc
intoabc\:abc
andabc:def:ghi
intoabc\:def\:ghi
.Moreover, you want to use:
instead. That would ensure that any backslashes in the user input do not escape any characters.