vimtricks.wiki Concise Vim tricks, one at a time.

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
  • .,+2 is a range: from the matched line through 2 lines below it
  • d deletes the entire range
  • The number 2 can 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,+1d to delete one line before and one line after each match
  • Use .,+0d (or just d) to delete only the matching line — same as :g/pattern/d
  • Combine with :t to copy blocks: :g/^def /.,+5t$ duplicates each function stub to the end of the file
  • Stack commands with |: :g/^#/.,+2s/TODO/DONE/g substitutes within each block before deciding whether to delete

Next

How do I encode and decode JSON data in Vimscript for configuration and plugin development?