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

How do I run an Ex command on all lines between two pattern matches?

Answer

:/start/,/end/ {command}

Explanation

Vim's range addressing lets you specify a line range using search patterns instead of explicit line numbers. By using :/pattern1/,/pattern2/, you target all lines from the first match of pattern1 to the first match of pattern2, then apply any Ex command to that range. This is invaluable when working with structured files where you need to operate on a specific section.

How it works

  • :/start/,/end/ — defines a range from the next line matching start to the next line matching end
  • You can append any Ex command: d (delete), s/old/new/g (substitute), y (yank), > (indent), norm (normal mode command), etc.
  • The search is forward from the current cursor position

Example

Delete everything between BEGIN and END markers (inclusive):

:/BEGIN/,/END/d

Indent all lines inside a function body:

:/function start/,/function end/>

Substitute only within an HTML <div> block:

:/<div>/,/<\/div>/s/old/new/g

Tips

  • Combine with :g for repeated sections: :g/BEGIN/,/END/d deletes every BEGIN...END block in the file
  • Use ?pattern? for backward search in ranges: :?start?,/end/d
  • Add offsets: :/start/+1,/end/-1d to exclude the marker lines themselves

Next

How do I return to normal mode from absolutely any mode in Vim?