How do I run a search and replace only within a visually selected region?
Answer
:'<,'>s/pattern/replacement/g
Explanation
When you make a visual selection and then type :, Vim automatically inserts '<,'> as the range — the marks for the start and end of the last visual selection. Any substitute command you run with this range will affect only the selected lines.
How it works
'<— the mark for the first line of the last visual selection'>— the mark for the last line of the last visual selection:'<,'>s/old/new/gruns the substitution only within those lines- After leaving Visual mode,
'<and'>persist — you can re-use them without reselecting - Add the
cflag (:'<,'>s/old/new/gc) to confirm each replacement interactively
Note: The range is line-based — even a character-wise visual selection uses the start and end lines, not the exact characters. For exact column-range substitution, use \%V (see tip below).
Example
You have a config file and want to change true to false only in the [production] section. Select those lines with V + motion, then:
:'<,'>s/true/false/g
Lines outside the selection are untouched.
Tips
- Use
\%Vin your pattern to constrain to the exact visual selection (character-wise)::'<,'>s/\%Vold/new/g - The marks
'<and'>can be jumped to directly:'<moves to the first line,`<moves to the exact character - Combine with
:gfor more power::'<,'>g/TODO/ddeletes all TODO lines within the selection - After a visual substitute, press
gvto reselect the original region for further operations