Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace the selected filepath in vim

Tags:

replace

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.
like image 298
ganqqwerty Avatar asked May 26 '26 17:05

ganqqwerty


2 Answers

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:

  • Search for the selected text
  • Refining search patterns with the command-line window.

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
like image 154
Peter Rincker Avatar answered May 30 '26 09:05

Peter Rincker


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

like image 37
Igor Avatar answered May 30 '26 10:05

Igor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!