Today I Learned

A Hashrocket project

Ready to join Hashrocket? Find Openings here and apply today.

How to restrict visually selected replace

Make a visual selection in vim, then type :. You can do a search and replace by the normal means:

:'<,'>s/something/something else/g

The only problem with this is that it defaults to the whole line. So if, for example, you are trying to replace the / character within a selection on a line of an HTML or template file, this will screw up the closing tag of that line.

The trick here is to use %V in the matching portion.

:'<,'>s/\%Vsomething/something else/g

This restricts the match criteria to just the selection! Checkout :help %V.

Every developer at Hashrocket is a Vim expert. Check out our development environment, Dotmatrix, and if you are in Chicago, come to the Vim Chicago Meetup hosted at our Chicago office.