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

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 matching start from the cursor position
  • , — range separator (from first match to second match)
  • /end/ — find the next line matching end after the first match
  • d — 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/g to replace only within a block
  • Add offsets: :/BEGIN/+1,/END/-1d to keep the delimiters but delete their contents
  • Use with :g for repeated blocks: :g/BEGIN/,/END/d deletes every BEGIN...END block in the file

Next

How do I ignore whitespace changes when using Vim's diff mode?