How do I use search patterns to define the start and end of an Ex command range?
Answer
:/pattern1/,/pattern2/
Explanation
Ex command ranges in Vim are not limited to line numbers and marks — you can use /pattern/ as a range boundary to select lines between any two matching patterns. This makes bulk operations precise and script-friendly without needing to know exact line numbers.
How it works
A range takes the form {start},{end} where each boundary can be:
- A line number:
1,5 - A mark:
'a,'b - A search pattern:
/pattern/ - The current line
.or last line$ - Offsets from any of the above:
/pattern/+1means the line after the match
Combine them freely:
:/function foo/,/^end/d
Deletes from the line containing function foo through the next line matching ^end.
Example
Given a file with sections:
## Setup
install deps
run tests
## Deploy
upload artifacts
push to server
## Cleanup
To substitute only within the Deploy section:
:/## Deploy/,/## Cleanup/s/push/deploy/g
To delete everything between Setup and Deploy (exclusive of headers):
:/## Setup/+1,/## Deploy/-1d
The +1 and -1 offsets let you skip the bounding lines themselves.
Tips
0as the start address searches from the top of the file (useful when the pattern may appear before the cursor)- Use
.for the current line as a start::.+1,/end/d - Patterns can be empty to reuse the last search:
:,//d - Works with any Ex command:
y(yank),m(move),co(copy),normal,s(substitute)