How do I delete each line matching a pattern along with a fixed number of lines that follow it?
Answer
:g/pattern/.,+2d
Explanation
Inside a :global command, . always refers to the current matching line — not the original cursor position. This lets you form a relative range like .,+2 to select a block of lines starting at each match, then apply a command to that block.
How it works
:g/pattern/marks every line that matches the pattern- For each marked line,
.resolves to that matched line .,+2is a range: from the matched line through 2 lines below itddeletes the entire range- The number
2can be any positive integer to control how many following lines to include
Example
Given a file with repeated three-line blocks:
## Task: Write tests
description line 1
description line 2
## Task: Fix bug
description line 1
description line 2
Running :%g/^## Task/.,+2d deletes every ## Task header and its two following lines:
(All blocks removed.)
Tips
- Use
.-1,+1dto delete one line before and one line after each match - Use
.,+0d(or justd) to delete only the matching line — same as:g/pattern/d - Combine with
:tto copy blocks::g/^def /.,+5t$duplicates each function stub to the end of the file - Stack commands with
|::g/^#/.,+2s/TODO/DONE/gsubstitutes within each block before deciding whether to delete