/ in vi Search and replace?

Viewed 71677

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?

6 Answers

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.

LINUXFORWARD vs. WINDOWSBACK (DIRECTORY SLASHES)

  • The slashes are literally reversed in Windows and easily stated for Linux
    • Windows:
    • C:\Program Files (x86)\Microsoft OneDrive\
    • Linux:
    • /usr/bin

SOLUTION

I'm only able to state the struggle for Vim's Find & Replace on Windows as i'm not on a Linux pc.

  • Fix is to double backslash
    • GOOD:
    • :%s/c:\\Program Files (x86)\\Microsoft OneDrive\\/annoyancereplaced/g
    • BAD:
    • :%s/c:\Program Files (x86)\Microsoft OneDrive\/unabletoreplaceannoyance/g
NOTE
  • If working with network paths where Windows uses two slashes \\ then that means for every backslash there needs to be another backslash as it's always kept even
    • e.g. network path: \\Foo\Bar\
    • %s/C:\\Program Files (x86)\\foo\\bar/\\\\Foo\\Bar\\
    • notice the \\\\
Related