Step 3 of 6

18. Ex Commands Addresses And Ranges

Useful address specifiers

There are a few useful address specifiers that are well worth remembering. These are:

  • ., which represents the current line
  • $, which represents the last line in the file — for example, :$d deletes the last line in the buffer
  • 't, which represents the line that mark t is set to
  • /foo/, which represents the next line where foo matches (relative to the cursor position) — for example, :/foo/d deletes the next line where the text foo appears
  • ?foo?, which represents the previous line where foo matches (relative to the cursor position) — for example, :?foo?d deletes the previous line where the text foo appears
  • You can offset an address with a positive or negative number, e.g. :+1d deletes the line one below the cursor, and :-1d deletes the line one before the cursor

You can also chain these specifiers for some interesting results. For example:

  • :/foo/+2d deletes the line that is two lines below the next match of foo
  • :0/import/d deletes the first line in the buffer that contains the word import
  • :/foo/?bar?d jumps to the next match of foo, then jumps back from there to the previous match of bar, then deletes that line

Have a play with these in the editor. The :delete command accepts any of these addresses — work through the checklist below to give four of them a spin.

  1. Delete the first line with address 0 Address 0 targets the line at the very top of the buffer, so the cursor doesn't matter here — type :0d and hit Enter.
  2. Delete the next line matching FOO /FOO/ addresses the next line where FOO matches — type :/FOO/d and hit Enter.
  3. Delete the line just after BAR +1 offsets the match by one line — type :/BAR/+1d and hit Enter. The BAR line itself will survive.
  4. Delete the last line with $ $ always addresses the last line, wherever it is — type :$d and hit Enter.
Delete the first line with address 0 Address 0 targets the line at the very top of the buffer, so the cursor doesn't matter here — type :0d and hit Enter.

Next: Delete the next line matching FOO

Loading editor…