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

How do I yank or delete a line range directly into a named register without selecting it visually?

Answer

:[range]yank {reg}

Explanation

Vim's :[range]yank and :[range]delete Ex commands let you capture arbitrary line ranges into a register from the command line, bypassing the need to move the cursor or enter visual mode. This is particularly powerful in scripts, macros, and when working with large files where scrolling to the target lines would be disruptive.

How it works

  • :[range]yank {register} — yank the specified lines into the named register
  • :[range]delete {register} — delete the specified lines and store them in the named register
  • The range uses standard Vim syntax: line numbers, marks, patterns, or relative offsets

Common range forms:

  • :1,10yank a — yank lines 1–10 into register a
  • :'a,'byank b — yank lines between marks a and b into register b
  • :/^def/,/^end/delete c — delete from the first def to the next end into register c
  • :.,.+5yank — yank 6 lines starting from the current line into the unnamed register

Example

Given a long file, you want lines 100–120 in register z without scrolling there:

:100,120yank z

Now :echo @z confirms the contents, and "zp pastes them anywhere.

To grab all lines containing TODO and paste them at the end:

:g/TODO/yank A
:$put a

Tips

  • Using an uppercase register (AZ) appends to the existing register contents — combine with :g to collect matching lines
  • :yank with no register targets the unnamed register "
  • Equivalent pattern for deletion: :5,10delete removes lines 5–10, leaving them in the unnamed register for paste

Next

How do I insert the current date or time into the buffer using Vim's built-in expression evaluation?