0

How can you escape special characters defined in a variable within sed? Basically like the syntax below

$ export SCOOBY_HOST=http://example.com/
$ sed -i "s/var scooby_host = \(.*\)/var scooby_host = '$SCOOBY_HOST'/" index.html
Error: sed: -e expression #1, char 54: unknown option to `s'

My attempts so far always cause this error

sed: -e expression #1, char 54: unknown option to `s'
Dean Christian Armada
  • 6,724
  • 9
  • 67
  • 116
  • 2
    Isn't this about picking the most convenient separator character? Doesn't sed choose the next character after the 's' to measure the "from" and "to"? In your case a better choice other than '/' would be something that is not likely to appear unencoded in an URI? Maybe, the character '|'? – Jeff Holt Nov 29 '19 at 04:07
  • 1
    You can't; `sed` doesn't take parameters, so there's no notion of automatically escaping something. All you can do is dynamically generate a `sed` script, which means the burden of ensuring that interpolated strings are already correctly escaped falls on you. One way to do that is to adapt the rest of the command so that no escaping is necessary, as Jeff Holt points out. – chepner Nov 29 '19 at 04:08
  • 3
    ...or you can choose a better tool than `sed`. See, f/e, the many non-`sed` approaches given in [BashFAQ #21](http://mywiki.wooledge.org/BashFAQ/021), particularly the `gsub_literal` function (implemented in awk). – Charles Duffy Nov 29 '19 at 04:09
  • ...the perl mechanism referring to environment variables for literal text to be substituted works well -- also given in the above-linked FAQ, or here at Stack Overflow in several similar (might I think duplicative?) questions. – Charles Duffy Nov 29 '19 at 04:11
  • In particular, note the comment in Bash FAQ 21 about not using `sed` to edit files; use an actual file editor like `ed` instead. – chepner Nov 29 '19 at 04:12
  • 1
    try `sed -i "s@var scooby_host = \(.*\)@var scooby_host = '$SCOOBY_HOST'@" index.html` . Good luck. – shellter Nov 29 '19 at 04:15
  • @shellter, thank you! Perfect answer!! – Dean Christian Armada Nov 29 '19 at 05:01

0 Answers0