In Vim, how would I go about inserting characters at the beginning of each line in a selection?

For instance, let's say I want to comment out a block of code by prepending '//' at the beginning of each line (assuming my language's comment system doesn't allow block commenting like /* */). How would I do this?

What is the meaning of the exclamation marks in the above answer? (:%s!^!//!)
–
HK_CHMay 31 '11 at 8:57

9

@HKK, normally one uses the forward slash character / as a delimeter for the search and replace command. In this case we are inserting a forward slash as part of the search and replace so we use an alternative delimeter, namely the exclamation character !
–
cyber-monkJun 7 '11 at 20:46

1

+1, had no idea you could use something else as the regex delimiter (here I was using / and having to escape the // in :s/^/\/\/ instead of writing :s!^!//)
–
HashbrownDec 18 '13 at 6:19

This command will replace each occurrence of 'search' with 'replace' for the current line only. The % is used to search over the whole file. To confirm each replacement interactively append a 'c' for confirm:

:%s/search/replace/c

Interactive confirm replacing 'search' with 'replace' for the entire file

Instead of the % character you can use a line number range (note that the '^' character is a special search character for the start of line):

:14,20s/^/#/

Inserts a '#' character at the start of lines 14-20

If you want to use another comment character (like //) then change your command delimiter:

Thats really simple :). If you are having trouble with it may be because you are typing a bar (the other symbol with your \ ) | instead of a capital I. I thought it was a | at first.
–
cokedudeFeb 28 '14 at 17:30

If I do "5." it deletes 5 character from same line. How do I make it delete 5 character at once from each line ?
–
Rahul PrasadJun 24 at 6:58

/^/ is just a dummy pattern to match every line. norm lets you run the normal-mode commands that follow. I// says to enter insert-mode while jumping the cursor to the beginning of the line, then insert the following text (two slashes).

:g is often handy for doing something complex on multiple lines, where you may want to jump between multiple modes, delete or add lines, move the cursor around, run a bunch of macros, etc. And you can tell it to operate only on lines that match a pattern.