How do I search and replace only within a visual block selection?
Answer
:'<,'>s/\%Vold/new/g
Explanation
The \%V atom restricts a search pattern to match only within the visual selection area, including visual block selections. This lets you perform substitutions on a rectangular column of text.
How it works
- Make a visual block selection with
<C-v> - Type
:to enter command mode (range'<,'>appears automatically) - Use
\%Vin the pattern to restrict matches to the selected block
Example
Given a table:
name status count
alice active 10
bob active 20
charlie active 30
To change active to done only in the status column:
<C-v>select just the status column:'<,'>s/\%Vactive/done/g
Why %V is needed
Without \%V, the '<,'> range operates on entire lines. So a substitution would replace matches anywhere on those lines, not just within the visual block. The \%V atom constrains the match to the visual area only.
More examples
" Replace zeros with dashes in a selected column
:'<,'>s/\%V0/-/g
" Delete content within the visual block
:'<,'>s/\%V.//g
" Replace spaces with underscores in selected area only
:'<,'>s/\%V /_/g
Tips
\%Vworks in regular searches too:/\%Vpatternsearches only within the last visual selection- This is essential for editing tabular data, log files, and fixed-width formats
- Combine with
\%Vat both ends for extra precision:\%Vold\%V - Documented under
:help /\%V