How do I run a command on lines between two search patterns?
Answer
:/start/,/end/command
Explanation
Vim allows pattern-based ranges in Ex commands, letting you operate on lines between two search matches. This is more flexible than line numbers because it adapts to file changes automatically — the range is defined by content, not position.
How it works
:/pattern/— refers to the next line matching the pattern:/start/,/end/— range from first match to second match- Any Ex command can follow:
d,s/old/new/g,normal,move, etc. ?pattern?— searches backwards instead of forwards
Example
Delete everything between BEGIN and END:
:/BEGIN/,/END/d
Indent lines between two function definitions:
:/^func start/,/^func end/>
Before:
# BEGIN
this will be
deleted
# END
After :/BEGIN/,/END/d:
(lines removed)
Tips
- Combine with offset:
:/pattern/+1,/end/-1dto exclude the boundary lines - Use
\cfor case-insensitive::/\cbegin/,/\cend/s/old/new/g - Chain with
gfor powerful operations::g/^class/,/^class/s/self/cls/g - The range is resolved at execution time, so it always finds current matches