Vim Copy Line
There are several ways to copy a line in Vim. I often need this when writing CSS. The slow way is to navigate to the line I want, yank it, go back and paste it. The most efficient way I can think to do that is to jump by searching with / and pressing <CR>. Then yank the line with yy. Then use the jump list, <ctrl-o>, to bounce back. And press p to paste the line below or P to paste the line above. Let’s watch a screencast of this method first:
But Vim has a better way to copy a line. And it doesn’t involve moving around at all. In fact, your cursor can stay in the same place and you can do this with one command, the ex :yank command:
:<line number>yank– copies the line number specified to your default register
Once you’ve yanked, just paste with p or P and you’re done. But wait, there’s more! There’s an even better way. Use the ex :copy command:
:<line number>copy.– copies the line number specified and pastes it to the line below
Now you’ve done the whole operation in a single command. But we’re not done yet! The ex :copy command has an alias t. Putting it all together:
:<line number>t.– copies the line number specified and pastes it to the line below
You can also use + or - before the line number to turn it into a relative line number. Or even use a range of lines with a comma. Here are some examples of this in action:
:281t.– Copy line 281 and paste it below the current line:-10t.– Copy the line 10 lines above the current line and paste it below the current line:+8t.– Copy the line 8 lines after the current line and paste it below:10,20t.– Copy lines 10 to 20 and paste them below:t20– Copy the current line and paste it below line 20
Now here’s a screencast of the same operation I did in the beginning, but using our new method for copying lines.
Demo of Copying Lines in Vim
How do I copy a line in Vim?
A simple way to copy a line in Vim is to use yy to yank the line and P (to paste above) or p (to paste below).
But a better way that does not involve moving your cursor is with the ex commands:
:t. - This command will copy the line number specified and paste it to the line below your cursor.
How do I yank a specific line in Vim?
You can yank a specific line in Vim using the ex yank command. Just call :yank and the number you specified will be yanked into your default register.
Why wouldn't I use yy and p to copy and paste the line?
Using yy to yank a line in Vim is a perfectly acceptable way of doing it. You can then move to the line you want and press p to paste. But you need to move your cursor around the file to do so. Sometimes it's easier to move less and by using these commands, you don't need to move anywhere.