Repeating through lines in vim

I have some lines of text like this:

firstName
lastName
email

Now I add private readonly string to the start of the first line. How do I repeat this edit for the other lines? (not manually visiting each line of course) (BTW I do realize this could be done with a regex, but I'm looking for a "vi way" if possible)

Just in case, I'm using VsVim


Solution 1:

Navigate up to firstName in Normal mode and type

qaIprivate readonly string <ESC>jq

This will record the macro (in register a) of you adding "private readonly string " to the beginning of the line, then moving one line down. If you want to repeat this macro twice (thus repeating the command for the next two lines), in command mode type 2@a on the lastName line, which will execute the macro twice more.


This method fulfills your requirement of "not manually visiting each line"; however it's a little heavyweight for your application.

If it's the typing of private readonly string that you object to, a quick solution is to make your edit on the first line, then move down to each line you want to make the edit and use . in Normal mode. This will repeat your last command (in this case adding the text to the line) with no fuss.

Solution 2:

Another way to do this is to using Visual Block mode:

  1. Start with your cursor at the beginning of the first line.
  2. Press Ctrl+v to enter Visual Block mode.
  3. Press j to move down, extending the selection to include the lines you want.
  4. Press I to go into (prepending) Insert mode.
  5. Type private readonly string.
  6. Press Esc. This will cause you to go back to command mode, and the text you typed will be repeated on each line before the start of your visual block selection (in this case, at the start of each line, since that's where you began the selection).