RanRag
RanRag

Reputation: 49537

How to yank the current line and the line above it in Vim?

What I need is to yank the current line and the line just above it.

For instance, in the following example:

3   My test line
4   Line above current line
5   My current line |(cursor)
6   Line below current line

How do I yank lines 5 and 4 when my cursor is located on line 5?

Upvotes: 3

Views: 1089

Answers (3)

ib.
ib.

Reputation: 28934

In addition to the Normal mode commands already mentioned in other answers, one can use the :yank Ex command on a corresponding range of lines. For example, to copy the current line along with the line above it (without moving the cursor) run

:-,y

Upvotes: 3

pb2q
pb2q

Reputation: 59607

For this simple case, yk will do the trick. This is yank followed by a motion of up one line.

Generally, use yNk, e.g. y3k to yank the current line and the preceding 3 lines.

If you need to return to the cursor position after the yank, set a mark and return to the mark after the yk:

mmyk`m

If you need only remain on the same line where you began the yank, not the same cursor position, ykj is shorter.

Upvotes: 6

Michael Berkowski
Michael Berkowski

Reputation: 270599

yk should do it, as in Yank in the direction of up one line, since y will accept the next keystroke as a motion, and k alone represents motion up one line.

If you need your cursor to return to its original position, just add a j as ykj. You will probably see the cursor move inelegantly on screen, but it gets the job done.

Upvotes: 9

Related Questions