tags:

views:

171

answers:

3

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

thx

A: 

You can use macros.

Pablo Santa Cruz
You can, but you really shouldn't.
innaM
+11  A: 

The command:

:%s/^/foo: /

...inserts foo: 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: /
tangens
Another good, more interactive method is to use visual block mode (ctrl-V) to select the first column, then `I` to insert - type what you need, hit escape, and it'll be added to all the lines. This of course works in any column, not just the first, and you can also use `A` to append, or `c` or `d`.
Jefromi
Err.... Hefromi: why didn't you make this an answer? It's a good one. Or could have been.
innaM
@Jefromi: You should make your comment an answer, ctrl-V is easier to use than `:s`.
too much php
I've seen some colleagues using ctrl-V but the advantage of `:s` is that it works on every vim and every vi.
tangens
:substitute is also much more powerful. BTW, :s can be used with lines visually selected.
Luc Hermitte
+1  A: 

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.

Walter