2

Replace /tmp/storequote with /tmp/tmpdata in sed:

sudo sed -i "s/\/tmp\/storequote/\/tmp\/tmpdata/g" config.py

It works fine,/ was escaped by \.I want to use string variable which contains special characters in sed.

string1='/tmp/tmpdata'
string2='/tmp/storequote'
sudo sed -i "s/$string1/$string2/g"  config.py

It encounter a issue:

sed: -e expression #1, char 8: unknown option to `s'

How to fix it?

  • 2
    The simple and common fix is to use an alternative separator for the `s` command, for example `s|$string1|$string2|g`. That said, I'd suggest to be very cafeful when you play with dynamic sed expressions as it is not only error-prone but unsafe if the shell variables are not strictly validated. – luciole75w Aug 05 '20 at 01:51

1 Answers1

3

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.

xhienne
  • 5,738
  • 1
  • 15
  • 34