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

How do I apply commands to specific line ranges?

Answer

:{start},{end} command

Explanation

Ex commands accept range specifiers that control which lines are affected. Ranges can use line numbers, marks, patterns, and special symbols.

How it works

  • :5,10d deletes lines 5 through 10
  • :.,$d deletes from current line to end of file
  • :%s/old/new/g works on all lines (% = 1,$)
  • :.,+5s/old/new/g works on current line plus 5 more

Example

:1,10s/foo/bar/g       " Replace in lines 1-10
:'<,'>sort              " Sort visual selection
:.,/pattern/d           " Delete from here to next match
:g/TODO/.+1,.+3d       " Delete 3 lines after each TODO

Tips

  • . means current line
  • $ means last line
  • % means all lines (same as 1,$)
  • '<,'> is the visual selection range
  • +N and -N add offsets to positions

Next

How do you yank a single word into a named register?