1

I am trying to use sed to replace a path in a file.

sudo sed 's/a/b/g' -i /tmp/test

However the variable is

a = /var/lib and 
b = /data/lib

How do I escape the slash?

Eric R. Rath
  • 1,939
  • 1
  • 14
  • 16
Tampa
  • 75,446
  • 119
  • 278
  • 425
  • possible duplicate of [Use slashes in sed replace](http://stackoverflow.com/questions/5864146/use-slashes-in-sed-replace) – tripleee Aug 14 '14 at 06:56

4 Answers4

6

The character just after the s command doesn't need to be a /. When working with paths, I use :, as in:

sudo sed 's:a:b:g' -i /tmp/test
mouviciel
  • 66,855
  • 13
  • 106
  • 140
2

You can change sed's delimiter for instance use # instead:

$ sed 's#/var/lib#data/lib#g'
/var/lib   
data/lib
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
2

this should work

sed  -i "s@$a@$b@g" /tmp/test

two things you need to take care about:

1) if you want to use variables in your sed line, use double quotes

2) delimiter could be other than "/", e.g. @, #, : ...

Kent
  • 189,393
  • 32
  • 233
  • 301
0

In sed(1), as in vi(1), the '/' is just the customary separator. It can be escaped with \, leading to "leaning toothpick syndrome" when munging path names:

sed -e 's/\/var\/lib/data\/lib/' ...

You can use another non-word character, e.g. ';':

sed -e 's;/var/lib;data/lib; ...

vonbrand
  • 11,412
  • 8
  • 32
  • 52