How to escape “/” in a sed command in Puppet script

escapingpuppetsed

In a config file, I'm trying to replace PREFIX=/jenkins with, say, PREFIX=/foobar.

On the (bash) command line, this works fine:

sed -i.bak s/PREFIX=\\/jenkins/PREFIX=\\/foobar/g /etc/default/jenkins

However, in a Puppet script (.pp file):

exec { 'Change-prefix':
  command => "sed -i.bak s/PREFIX=\\/jenkins/PREFIX=\\/foobar/g /etc/default/jenkins",
  path    => ["/bin"],
}

produces:

err: /Stage[main]//Exec[Change-prefix]/returns: change from notrun to 0 failed:
sed -i.bak s/PREFIX=\/jenkins/PREFIX=\/foobar/g /etc/default/jenkins 
returned 1 instead of one of [0] 

How to escape the sed command properly? Or is something else the matter?

I also tried with \\\/, but that yields: warning: Unrecognised escape sequence '\/'

Best Answer

In cases where your sed expression contains a '/', you may want to consider using a different delimiter. I chose the pipe symbol in this example.

sed -i.bak 's|PREFIX=/jenkins|PREFIX=/foobar|g' /etc/default/jenkins

Using this syntax in your Puppet manifest would be a lot cleaner and more readable, in my opinion.


From the sed info page:

\%REGEXP%' (The%' may be replaced by any other single character.)

 This also matches the regular expression REGEXP, but allows one to
 use a different delimiter than `/'.  This is particularly useful
 if the REGEXP itself contains a lot of slashes, since it avoids
 the tedious escaping of every `/'.  If REGEXP itself includes any
 delimiter characters, each must be escaped by a backslash (`\').