How do I search and replace only within a visual selection?
Answer
:'<,'>s/old/new/g
Explanation
After making a visual selection, you can run a substitute command that only affects the selected text. Pressing : in visual mode automatically inserts '<,'> as the range.
How it works
- Select text with
v,V, or<C-v> - Press
:to enter command mode (shows:'<,'>) - Type
s/old/new/gand press Enter - Only selected lines are affected
Example
Select lines 2-4 and run :'<,'>s/foo/bar/g to replace only within those lines.
Tips
'<is the mark for the start of the last visual selection'>is the mark for the end- For block selections (
<C-v>), use\%Vto restrict to the block::'<,'>s/\%Vold/new/g - Without
%, the range is the selected lines