Vim Trick: How to Completely Replace a Line With Copied Text

Tue Oct 24 2017 | Tricks  | 0 Comments

Have you ever found yourself doing the following:

  1. Copying a line (yy)

  2. Moving down a few lines (j)

  3. Pasting in your copied line above the line you're trying to replace (p)

  4. Moving to the line you were trying to replace and deleting it (dd)

  5. Getting frustrated because you want to replace another line with your original line somewhere else, but realize that your buffer is now filled with the line you just deleted so you now have to copy the original line again (yy) before starting the whole process over again.

Don't worry. There's a better way.

While the keystrokes for this trick aren't quite as finger-friendly as I would like, it still saves a ton of time and frustration.

  1. Y (shortcut for yy)

  2. Move to the line you want to replace

  3. V"0p

  4. Repeat steps 2 and 3 indefinitely


vim replace line


Breaking it down

  • Y copies (yanks) the entire line

  • V switches to visual mode and highlights the entire line

  • " is how you access Vim's registers. Registers are basically clipboards Vim uses to save data for later. For more info on registers visit http://www.brianstorti.com/vim-registers

  • 0 is a special register Vim uses to store your last yanked text

  • p pastes the previously specified register


Hi.

My name is Aaron Schwartz. I write code all day long for a living. Vim (and Vim emulation in IDE's) has made coding much more pleasant.

Learning Vim can be challenging but I'm convinced that anybody can learn it with a little time and the right instruction.

My goal is to make it as easy as possible to memorize enough Vim to be comfortable using it every day.


Want To
Memorize Vim
Quickly?

Receive weekly emails with the tactics I used to go from novice to expert.


Recent Posts


This site was coded in WebStorm with Vim emulation enabled. Powered by the React Static framework.