5

I find it sometimes useful to add a certain string to the beginning of a line, and sometimes I would like to do this to a few lines, and I don't like moving to each line and change it. Assuming I know how to select the lines that interest me in Visual mode, how can I add the prefix?

0

3 Answers 3

10

What I do to achieve this is to make a visual rectangular selection with Ctrl-V at the place where I want to add the prefix, and once all lines are selected, just press I (that's a capital i) and type in the text. When exiting insert mode the text will be copied to all the lines.

This is the sequence in images:

  • Visual selection of the place of insertion

vim1

  • Type in the text

vim2

  • Back to normal mode and the insertion is done

vim3

Note that this works anywhere, not only at the beginning of the line.

1
  • Is it possible to do this using visual mode opposed to block mode?
    – lsl
    Commented Oct 23, 2019 at 6:36
3

Usually it goes like this for me:

Esc + Shift-V + select lines + :
s//prefix[Enter]

Edit: Why I like it is that it's still quick and when sometimes you want to use something more then this is nice base to start from, like next adding line numbers, ore expanding regex further

s//\=printf('%2d', line('.'))
2

Assuming you'd like to add prefix to 5 lines at the beginning of the line, then you can use Search and replace:

:.,+5s/^/prefix_/g

or at the end of the lines:

:.,+5s/$/suffix_/g

See more at: How to comment out a set of lines which are selected in visual mode?

Not the answer you're looking for? Browse other questions tagged or ask your own question.