vimtricks.wiki Concise Vim tricks, one at a time.

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

  1. Make a visual block selection with <C-v>
  2. Type : to enter command mode (range '<,'> appears automatically)
  3. Use \%V in 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:

  1. <C-v> select just the status column
  2. :'<,'>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

  • \%V works in regular searches too: /\%Vpattern searches only within the last visual selection
  • This is essential for editing tabular data, log files, and fixed-width formats
  • Combine with \%V at both ends for extra precision: \%Vold\%V
  • Documented under :help /\%V

Next

How do I always access my last yanked text regardless of deletes?