How do I run an Ex command on all lines between two pattern matches?
Answer
:/start/,/end/ {command}
Explanation
Vim's range addressing lets you specify a line range using search patterns instead of explicit line numbers. By using :/pattern1/,/pattern2/, you target all lines from the first match of pattern1 to the first match of pattern2, then apply any Ex command to that range. This is invaluable when working with structured files where you need to operate on a specific section.
How it works
:/start/,/end/— defines a range from the next line matchingstartto the next line matchingend- You can append any Ex command:
d(delete),s/old/new/g(substitute),y(yank),>(indent),norm(normal mode command), etc. - The search is forward from the current cursor position
Example
Delete everything between BEGIN and END markers (inclusive):
:/BEGIN/,/END/d
Indent all lines inside a function body:
:/function start/,/function end/>
Substitute only within an HTML <div> block:
:/<div>/,/<\/div>/s/old/new/g
Tips
- Combine with
:gfor repeated sections::g/BEGIN/,/END/ddeletes everyBEGIN...ENDblock in the file - Use
?pattern?for backward search in ranges::?start?,/end/d - Add offsets:
:/start/+1,/end/-1dto exclude the marker lines themselves