Sed allows you to use other separators than /
in a substitution.
For example, with a colon:
sudo sed -i "s:$string1:$string2:g" config.py
Now suppose string1
(or string2
) contains a colon, you'll again get a broken sed command. Same if they contain a semi-colon, which is used to separate sed
commands.
If you use bash, one solution to easily escape those special characters is to carefully choose a separator that has a special meaning for bash (like |
), and use printf %q
which will escape it for you, while keeping your command readable:
printf -v sed_command 's|%q|%q|g' "$string1" "$string2"
sudo sed -i "$sed_command" config.py
Warning: this hack won't escape dot characters in string1
which will retain their special meaning (i.e. any character). Keep in mind this is a hack that saves you from having headaches escaping possible special char.