tags:

views:

600

answers:

3

in vi, search and replace, how do you escape a '/' (forward slash) so that it is correct. Say in a path.

like: /Users/tom/documents/pdfs/

:%s//Users/tom/documents/pdfs//<new text>/g  --FAILS (obviously)

:%s/\/Users/tom/documents/pdfs\//<new text>/g -- FAILS with a trailing error

:%s/'/Users/tom/documents/pdfs/'/<new text>/g -- FAILS with a trailing error

What am I missing?

+10  A: 

You need to escape the forward slashes internally, too.

:%s/\/Users\/tom\/documents\/pdfs\//<new text>/g
Sarah Vessels
@Sarah - Doh! Yes, thank you!
JT
+16  A: 

Alternatively you can do :%s,foo/bar/baz,foo/bar/boz,g - I almost never use slashes because of the escaping confusion.

meder
Dude, I didn't know about that! I'm guessing you could use any character to delimit the fields then?
Sarah Vessels
Yeah I believe so, I just got accustomed to commas.
meder
You beat me by a few seconds :)
Bob
Nice tip! You can also save yourself the repetition with the `n` flag, which does the search without the replace. e.g. `:%s,foo/bar/baz,,gn`
nelstrom
Didn't know that it will work commas. I got accustomed to `%s:old/old:/old/new:g`
vbd
+4  A: 

As Sarah suggested, you need to escape ALL forward slashes.

You could instead use another character besides forward-slash as the delimiter. This is handy if your search string has a lot of slashes in it.

:%s#/Users/tom/documents/pdfs/#<new test>#g

This works perfectly in vim. I'm not 100% sure about vanilla vi.

Bob
I can't think of how you'd even get at vi these days. I was thinking most major Linux distros just redirect 'vi' to vim with lots of features turned off.
Sarah Vessels
Because linux isn't the only os :)Many of the BSDs ship with vanilla vi or nviMost of the commercial unix systems do as well. I remember (unhappily) the days of having to compile vim on IRIX because I couldn't live with vanilla vi.
Bob
Not too long ago Debian linked vi to nvi, as did NetBSD, FreeBSD, and OpenBSD. Some also shipped with vim-as-vim.
DigitalRoss