vim copy and paste commands

vim copy and paste FAQ: How do I copy and paste in vim (the vi or vim editor)?

In this short vi/vim tutorial I thought I'd share the most common vim copy and paste commands I use on a daily basis. I've been using vi (and vim) for almost 20 years now (wow), and these are the most common copy/paste commands I use.

vi/vim copy command

vim copy command: To copy the current line (the line where the cursor is currently positioned) to the vi buffer, make sure you're in vi command mode (i.e., hit the [Esc] key), and then enter the vi "yank" command, like this:

yy

Similarly, to copy five lines in vim, use the yank command again, but precede it with the number 5:

5yy

Although the "yy" command stands for "yank", you're really copying the lines to the vi buffer, which is similar to the operating system clipboard, but local to only your vi/vim editor.

vim paste commands

vim paste command: After you've used a vi/vim copy command like the ones shown above to copy the contents to the buffer, you can then use the vim paste command to paste the contents to another location in your file.

To paste the buffer contents below the current line, use the vim paste command, a lowercase letter 'p':

p

If instead you want to paste the contents above the current line position, use an uppercase letter 'P' instead, like this:

P

More advanced vi/vim copy and paste commands

I probably use those vim copy and paste commands 99% of the time when I'm working with vi (and vim), but there are also more powerful (and complex) copy/paste commands you can issue from the vi last line mode. Here are a few more examples.

To copy lines 1 through 20 of the current file to your current cursor position, use this command:

:1,20 co .

If you're not familiar with vi's last line mode, first make sure you're in vi command mode by pressing the [Esc] key. Then when you type the letter ":", whatever you type in vi will appear on the last line of the editor window. (Hence the name "last line mode".) After entering last line mode, the 1,20 co . part of the command tells vi to copy lines 1 through 20 to the current location. In vi, the current location (current cursor position) is always referred to by the decimal character ("."). After typing the command shown, just press [Enter], and the copy and paste command should be executed as described.

vi/vim copy and paste summary

If you have any question, comments, or would like to share your own vi and vim copy/paste commands, feel free to use the comment form below. Also, if you prefer videos, I discuss these techniques in my "Vim - Deleting Text video tutorial" on YouTube.

Post new comment

The content of this field is kept private and will not be shown publicly.