Search and replace in visual selection in Vim

on January 23, 2017. in Software, Blablabla. A 1 minute read.

The search and replace feature is very powerful in Vim. Just do a :help :s to see all the things it can do.

One thing that always bothered me though, is that when I select something with visual, try to do a search and replace on it, Vim actually does it on the entire line, not just on the selection.

What the…? There must be a way to this, right?

Right. It’s the \%V atom.

Instead of doing :'<,'>s/foo/bar/g to replace foo with bar inside the selection, which will replace all foo occurences with bar on the entire line, the correct way is to use the \%V atom and do :'<,'>s/\%Vfoo/bar/g.

I’m using this approach in the HugoHelperLink fuction of my Vim Hugo Helper plugin.

Happy hackin’!

Tags: vim, search, replace.