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

How do I specify line ranges in Ex commands to target specific parts of a file?

Answer

:{range}command

Explanation

Every Ex command in Vim can be preceded by a range that specifies which lines it should operate on. Mastering ranges transforms simple commands like :d, :s, :y, and :normal into precision tools that act on exactly the lines you want — no visual selection required.

Range syntax

Range Meaning
. Current line
$ Last line in the file
% Entire file (shorthand for 1,$)
N Line number N (e.g., 10)
'a Line of mark a
'<,'> Last visual selection
/pattern/ Next line matching pattern
?pattern? Previous line matching pattern

Ranges can be combined with offsets using + and -:

Range Meaning
.,.+5 Current line through 5 lines below
.-3,. 3 lines above through current line
.,$ Current line through end of file
1,. Beginning of file through current line
/start/,/end/ From next start match to next end match
'a,'b From mark a to mark b

Example

Delete lines 10 through 20:

:10,20d

Yank from the current line to the end of the file:

:.,$y

Substitute only between two patterns:

:/BEGIN/,/END/s/old/new/g

Copy the current line and the next 4 lines to after line 50:

:.,.+4t50

Run a normal mode command on lines 5 through 25:

:5,25norm A;

Tips

  • % is the most commonly used range — it means the entire file and is equivalent to 1,$
  • Visual selection automatically populates '<,'> as the range when you press : from visual mode
  • Use .+1,$-1 to target everything except the first and last lines relative to the cursor
  • Pattern ranges are evaluated at execution time — /start/,/end/ finds the next start from the cursor, then the next end after that
  • Combine ranges with :g for even more power: :10,50g/TODO/d deletes TODO lines only within lines 10-50
  • The :number command itself uses ranges: :10,20number (or :10,20#) prints lines 10-20 with line numbers
  • Use 0 as a destination (not a range) with :t and :m to place text before line 1: :5t0 copies line 5 to the top of the file
  • Ranges work with nearly every Ex command: :w, :d, :y, :s, :g, :normal, :t, :m, :!, :read, and more

Next

How do I edit multiple lines at once using multiple cursors in Vim?