ganqqwerty
ganqqwerty

Reputation: 2004

Search and replace the selected filepath in vim

I often work with files full of filepaths inside. I want to be able to quickly select my filepath in Visual Mode and replace it with some other filepath.

For example I have the file like this:

balvadsd /mnt/Windows/Documents\ and\ Settings/stuff/file.exe blablabalba albla
/mnt/Windows/Documents\ and\ Settings/stuff/file.exe bla2 vslva 21 
stuff foo bar dsad /mnt/Windows/Documents\ and\ Settings/stuff/file.exe 

I need to

  1. search for all occurrences of /mnt/Windows/Documents\ and\ Settings/stuff/file.exe
  2. replace my path /mnt/Windows/Documents\ and\ Settings/stuff/file.exe with some other path. The tricky bit is that the solutions like this one don't work with filepaths because of slashes, backslashes and dots.

Upvotes: 3

Views: 4976

Answers (2)

Peter Rincker
Peter Rincker

Reputation: 45177

You can escape the regex metacharacters with \. So foo/bar becomes foo\/bar for your regex. Or you can use a different seperator like #. However you still need escape the .. You can avoid the need to escape . and other regex metacharacters by using \V for very nomagic. Using \V means all regex metacharacters now must be escaped meaning non escaped charters match their literal selves.

:%s#\V/mnt/Windows/Documents\ and\ Settings/stuff/file.exe#replacement#g

However all that escaping can become annoying. I usually use a visual star mapping and/or plugin. Meaning I visually select the text then press *. Then you can just do :%s//replacement/ or :%s##replacement# to make the replacement.

There are some nice Vimcast episodes by Neil Drew that talk about this:

You can take this idea further with the gn motion and the . command. See the following vimcast episode: Operating on search matches using gn.

For more help see:

:h /\V
:h gn

Upvotes: 4

Igor Pejic
Igor Pejic

Reputation: 3698

Instead of using slashes in the body of the substitute command you can use any other single-byte character, but not an alphanumeric character, '\', '"' or '|'. (in this example @).

%s@/mnt/Windows/Documents\\@/some/other/path

Upvotes: 1

Related Questions