How do I run a substitution only within the exact characters of my visual selection?
Answer
:%s/\%Vpattern/replacement/g
Explanation
The \%V atom restricts a regex match to the last visual selection — more precisely than :'<,'>s/..., which operates on whole lines. With \%V, the substitution only affects characters that were inside the visual selection, letting you replace in the middle of lines without touching surrounding text.
How it works
- Make a visual selection (characterwise
v, linewiseV, or blockwise<C-v>) - Press
<Esc>to exit visual mode (the selection is preserved as'<and'>) - Run the substitution with
\%Vin the pattern:
:%s/\%Vpattern/replacement/g
The % range covers the whole file, but \%V inside the regex causes matches to be skipped if they fall outside the visual selection boundaries.
Example
Given this line, with only the middle word visually selected:
foo bar baz
^^^
Running :%s/\%Va/X/g changes only the a inside the selection:
foo bXr baz
Without \%V, all three a characters across the file would be affected.
Tips
- You can also scope with
:'<,'>s/\%Vpattern/replacement/gto limit both by line range and visual boundaries - Works with all visual selection types: characterwise, linewise, and blockwise
- The
\%Vatom matches zero-width, so it can be placed at the start of the pattern or between atoms - Use
\%>'<and\%<'>as lower-level alternatives to bracket the selection manually