history 13 of 36
How to Comment Out All Lines in the VI Editor
Comment out every line of a file in vi with one search-and-replace command, plus how to comment a range, undo it and use Vim visual block mode.
Written
From my Linux study notes, 2014. Some commands and versions here are old, so please reuse them carefully. Anything marked "added later", and the notes at the end, explain what has changed since.
This can be done with a command like “search and replace”.
-
Open the file in the
vieditor. -
Press Escape and type:
:1,$s/^/##/g -
Press Enter.
Every line in the file now starts with ##.
How the command breaks down
:1,$s/^/##/g can be broken down as:
| Part | Meaning |
|---|---|
: |
Starts a command on the vi command line (you must be in normal mode, which is why you press Escape first). |
1 |
Start from the first line. |
,$ |
End at the last line ($ means the last line of the file). |
s |
The substitute (search and replace) command. |
/^ |
Search for the start of the line (^ matches the start of each line). |
/## |
Replace with ##. |
/g |
Replace all occurrences on each line. |
Correction to the original breakdown: the original listed $s as “end at the last line”. Strictly, $ alone is the last line and s is the separate substitute command. The command itself is correct.
The g flag is harmless here but not needed, because the start of a line can only match once per line. :1,$s/^/##/ does the same thing.
Notes for today
Shorter form
% means “every line in the file” and is the same as 1,$:
:%s/^/#/Use whichever comment character the file needs: # for shell scripts and most Linux config files, // for languages such as C or JavaScript. Because / is the separator in the command, escape it with a backslash, or use a different separator:
:%s#^#//#Comment only some lines
Give a line range instead of the whole file. This comments lines 10 to 20:
:10,20s/^/#/Type :set number to show line numbers so you can see which range you need.
Remove the comments again
Replace ## at the start of each line with nothing:
:%s/^##//If you made a mistake, press u in normal mode to undo the last change.
Visual block mode (Vim only)
On most modern distributions the vi command actually runs Vim, which also lets you comment a block of lines by selecting it. Classic vi does not have this feature; if it does not work, install the full vim package.
- Move the cursor to the first character of the first line you want to comment.
- Press
Ctrl-vto start visual block mode. - Move down with
j(or pressGto go to the last line) to select the lines. - Press
Shift-i(capitalI) to insert at the start of the block. - Type
#. - Press Escape. The
#appears on every selected line after you press Escape.
To uncomment, select the column of # characters with Ctrl-v and the movement keys, then press x to delete them.
Check it worked
Save and quit with :wq, then look at the start of the file:
head file-name