/ in vi Search and replace?

in vi, search and replace as you avoid the "/" (slash) so that it is correct. Say along the way.

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?

+48
vim replace text
Nov 06 '09 at 0:32
source share
5 answers

You also need to avoid the slash.

 :%s/\/Users\/tom\/documents\/pdfs\//<new text>/g 
+55
Nov 06 '09 at 0:34
source share

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

+94
Nov 06 '09 at 0:36
source share

As Sarah suggested, you need to avoid all the slashes.

Instead, you can use a character other than scrolling as a separator. This is useful if there are a lot of slashes in your search bar.

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

This works fine in vim. I am not 100% sure about vanilla vi.

+14
Nov 06 '09 at 0:37
source share

I know this question is several years old, but for others who can land on it looking for an easier solution, in 2014 you can replace the β€œ/” separator with something else, like β€œ!” If you do this in front in the middle and back, for example:

 :%s!foo/bar/baz!foo/bar/boz!g 

It is very similar to Meder's answer ... But, I believe that the exclamation is much easier to consider as a separator. And I just wanted to confirm that this method still works in the current version of VIM that I use on Mac OSX Mavericks.

+3
Nov 06 '14 at 17:06
source share

Can you use ? For search

If you search for a pattern in the register, and the pattern contains the character "/", can you just use the command ? instead of command / from normal mode to start pattern matching. In this case, the '/' char is no longer needed. (however you need to escape the '?' char now)

? will search in the opposite direction / , therefore, if you are not against the direction of the search, and your search template does not contain "?" char.

Also check out the escape() script if you want more.

+2
Aug 4 '15 at 9:12
source share



All Articles