Step 4 of 6

18. Ex Commands Addresses And Ranges

Ranges

A range is used to tell Vim “I’m talking about this range of lines”. A range is specified as two addresses — the lines between the two addressed lines (inclusive) constitute the range.

To specify an range, you prefix the command like so:

:[address1],[address2]command

If command supports an range, this will cause it to operate on the range you’ve specified. The range is inclusive, so the range 1,3 will operate over lines 1, 2, and 3.

For example, if you wanted to delete the first ten lines in the buffer, you could use:

:1,10d

There is only one special range, and it’s one that you might have seen before: %. The % range is a synonym for 1,$ — that is, it captures all of the lines in the buffer. For example, :%d will delete all of the lines in the buffer (if you’re feeling bold).

The great thing about ranges is that the upper and lower bounds are just addresses. You can use all of the powerful Ex mode addressing tricks we’ve discussed above to specify a range! For example:

  • :/foo/,/bar/d will move to the next line matching foo and delete from there until the next line matching bar
  • :/foo/+1,/bar/-1d will do the same as above, but won’t delete the foo and bar lines.

Let’s try this in the editor. Work through the checklist below — the buffer walks you through each range as you go.

  1. Delete lines 5 through 10 Two literal line numbers make the simplest range — type :5,10d and hit Enter.
  2. Delete the START…END block with a pattern range Both ends of a range are just addresses — :/START/,/END/d deletes from the next START match through the next END match.
  3. Wipe the whole buffer with % % is shorthand for 1,$ — type :%d and hit Enter to leave nothing behind.
Delete lines 5 through 10 Two literal line numbers make the simplest range — type :5,10d and hit Enter.

Next: Delete the START…END block with a pattern range

Loading editor…