1

I'm surprised this hasn't been asked yet, but how do I copy non-consecutive lines into the buffer at once?

For example, let's say my file looks like this:

1
2
3
4
5
6
7
8
9
10

What commands can I use to copy lines 1, 3, and 5 at once? Therefore, when I pasted at the end of the file, it'd look like this:

1
2
3
4
5
6
7
8
9
10
1
3
5
1
  • "I'm surprised this hasn't been asked yet". I've heard/read this question hundreds of times.
    – romainl
    Commented Jan 25, 2023 at 19:37

2 Answers 2

2

You can "append" to a register when you yank or delete by using its uppercase name, so "Ayy yanks the line into the a register, but keeps the old contents, too. A quick way to empty a register is qaq, which starts recoding in a and then stops without adding anything.

So qaq, then 3G"Ayy or :5yank A would continue to append lines to the a register which you can later paste like "ap or :$put a.

If your lines share a common pattern, you can use

:global/pat/yank A

to yank them all in a single command (again, prefixed by qaq as needed to clear the register).

If the only goal is "copy to end of buffer," using :t$ (equivalent to :copy $) is probably easier.

1
  • Thank you; this was actually the solution I was looking for. Appending to a register seems like it could be very useful to me going forward!
    – qotsa42
    Commented Jan 26, 2023 at 15:50
2

If you can only reference those lines by their number, then there is no built-in, dedicated command for that.

But something like this:

:1t$|3t$|5t$

doesn't strike me as particularly hard or slow.

This variant:

:t$<CR>
:3@:|5@

is not too bad either, if less intuitive, IMO.

If you can reference those lines by a search pattern, then you can use :help :g:

:g/<pattern>/t$

With your sample:

:g/^[135]$/t$

Did you consider looking for an existing plugin?

7
  • Don’t forget you could also yank-append to a register if need be (e.g., qaq:g/pat/y A)
    – D. Ben Knoble
    Commented Jan 25, 2023 at 20:18
  • I did not consider any plugins; I figured that if there wasn't an easy way to append to the register or mass-copy specific lines it wasn't really worth pursuing. Thanks for your response -- what exactly does the pipe character do your first suggestion?
    – qotsa42
    Commented Jan 25, 2023 at 20:54
  • @D.BenKnoble That would be pointless in this case. :t does the job more intuitively, efficiently, and without polluting registers.
    – romainl
    Commented Jan 25, 2023 at 20:54
  • @qotsa42 see :help :bar.
    – romainl
    Commented Jan 25, 2023 at 20:56
  • @D.BenKnoble I can't get that command to work; is that supposed to be a macro?
    – qotsa42
    Commented Jan 25, 2023 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.