Reputation: 935
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?
Upvotes: 73
Views: 79570
Reputation: 101
Windows uses backslash for directories and Linux uses forward slash for directories. Vim is a text editor that works for operating-systems. Since both os have different directory path interpretation regarding how slashes are used, Vim must then need a way to interpret Windows twisted method.
C:\Program Files (x86)\Microsoft OneDrive\
/usr/bin
I'm only able to state the struggle for Vim's Find & Replace on Windows as i'm not on a Linux pc.
:%s/c:\\Program Files (x86)\\Microsoft OneDrive\\/annoyancereplaced/g
:%s/c:\Program Files (x86)\Microsoft OneDrive\/unabletoreplaceannoyance/g
\\
then that means for every backslash there needs to be another backslash as it's always kept even
\\Foo\Bar\
%s/C:\\Program Files (x86)\\foo\\bar/\\\\Foo\\Bar\\
\\\\
Upvotes: 0
Reputation: 1178
You can use ?
to search
In case of searching pattern in a register, and the pattern contains a '/' character, you can simply use ?
command instead of /
command from normal mode to start pattern matching. In such case, no more escape required for '/' char. (however you need to escape '?' char now)
?
will search in the opposite direction of /
, so if you don't mind the search direction, and your search pattern doesn't contains '?' char.
In addition, check the escape()
script if you want more.
Upvotes: 5
Reputation: 3918
I know this question is several years old, but for others who may land upon this one searching for an easier solution, in 2014, you can substitute the "/" delimiter for something else like "!", as long as you do it in front, middle, and back, like this:
:%s!foo/bar/baz!foo/bar/boz!g
Very simiar to Meder's answer ... But, I find that the exclamation is a lot easier to view as a separator. And I just wanted to confirm that this method still works in the current version of VIM, which I am using in Mac OSX Mavericks.
Upvotes: 7
Reputation: 811
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.
Upvotes: 19
Reputation: 186562
Alternatively you can do :%s,foo/bar/baz,foo/bar/boz,g
- I almost never use slashes because of the escaping confusion.
Upvotes: 136
Reputation: 31640
You need to escape the forward slashes internally, too.
:%s/\/Users\/tom\/documents\/pdfs\//<new text>/g
Upvotes: 70