Say that I am on line 20 and I would like to yank line 4, how can I do that?
And similarly, how can I yank a line relative to my cursor position, say the one 3 lines up?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communitySay that I am on line 20 and I would like to yank line 4, how can I do that?
And similarly, how can I yank a line relative to my cursor position, say the one 3 lines up?
From :help :yank
:
:[range]y[ank] [x] Yank `[range]` lines [into register x].
So, to yank line 4, one would type:
:4yank
Note you can easily do this from insert mode with <C-o>
; this allows you to
execute one command, after which you're returned to insert mode; for example:
<C-o>:4yank
You can, of course, also use other ranges. Some examples:
:1,3yank
:%yank
:.,$:yank
:.,+3yank
:-3,.yank
:-3yank
The most useful things to remember about ranges:
:line1,line2command
..
is the current line (you can actually omit the dot in most cases; :.,+3yank
and :,+3yank
are the same)+n
and -n
.By default the lines will be yanked into the default register (""
). If you want to use a named register, add a space an then the name of the register (naked, not prefixed with a double quote), eg:
:30,30yank a
> 10 lines yanked into "a
See :help [range]
for more
information.
:4yank
with :4y
– NewbieOnRails
May 12 '15 at 18:44
In addition to Carpetsmoker's answer, I should point out the awesome :help :m
and :help :t
.
If you want to copy line 4 to right below the current line you can do this:
:4t.
or that, if you want to copy that line right above the current line:
:4t-
Besides the ex-mode commands that you've got you can achieve that also it in command mode, e.g. by: 4GY''
- which means: goto line 4 (4G
), yank line (Y
), and return to previous line (''
).
You can also use jump marks; for your second question, e.g. by: mm3kY'm
- which means: set mark m (mm
), go three lines up (3k
), yank line (Y
), return to mark m ('m
).
Simply type
:4y
to yank line 4
it will go into the unnamed register. Then, (for example) you can use p
to put it elsewhere. You can also use [n]p
, e.g. 10p to paste it 10 times.
You can put it into a named register such as "a" with
:4y a
You can do
:10y <Enter> (to copy the line 10)
p (paste line 10 where the cursor is)
Setting up relative number helps in moving between lines of code as well.
:set relativenumber
Now you can copy the 5th line above the cursor with:
:-5y <Enter>
:p (to paste)