How to insert a word/text in the beginning of each line

Vim

Vim Problem Overview


Just want to insert a word or text at the beginning of range of lines, or the entire file. How do it in vim?

Vim Solutions


Solution 1 - Vim

The command:

:%s/^/foo: /

...inserts foo: (including a trailing space) at the beginning of each line.

For a range you can use line numbers:

:10,20s/^/foo: /

...will do it for line 10 to 20.

My preferred way to do it for a range of lines is this: move the cursor to the first line of the range, then enter ma to set the marker a to the current line. Move to the end of the range and enter

:'a,.s/^/foo: /

Solution 2 - Vim

I've become much more accustomed to use visual blocks for this kind of thing:

  • Move to the start of the first line in your range (gg for first line, ^ to move to the start)
  • <C-V>
  • Move down to the last line in your range
  • Ifoo<ESC>

That would insert foo at the start of each line.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvehomzzzView Question on Stackoverflow
Solution 1 - VimtangensView Answer on Stackoverflow
Solution 2 - VimWalterView Answer on Stackoverflow