How do I use search patterns as line ranges in Ex commands to operate on a block of text?
Answer
:/start/,/end/d
Explanation
Instead of specifying line numbers for Ex command ranges, you can use search patterns. Vim finds the next line matching each pattern and uses those lines as the range boundaries. This is powerful for operating on blocks of text defined by their content rather than their position.
How it works
:/start/— find the next line matchingstartfrom the cursor position,— range separator (from first match to second match)/end/— find the next line matchingendafter the first matchd— delete all lines in that range (or use any Ex command:y,s/old/new/g,m$, etc.)
The search is forward from the current cursor position for the first pattern, and forward from that match for the second pattern.
Example
Given this file with the cursor on line 1:
keep this
BEGIN
remove this line
remove this too
END
keep this too
Running :/BEGIN/,/END/d deletes lines 2 through 5:
keep this
keep this too
Tips
- Use
?pattern?for backward search::?START?,/END/d - Combine with substitute:
:/class/,/end/s/old/new/gto replace only within a block - Add offsets:
:/BEGIN/+1,/END/-1dto keep the delimiters but delete their contents - Use with
:gfor repeated blocks::g/BEGIN/,/END/ddeletes every BEGIN...END block in the file