How to Comment Lines in vi

In vi or vim, you can comment a range of lines by using a substitution command. This is handy when editing shell scripts, configuration files or temporary notes.

Comment every line in the file

Open the file in vi, press Esc, then run:

:1,$s/^/#/g

This adds # at the start of every line.

Use a different comment marker

To add ## at the start of each line instead:

:1,$s/^/##/g

What the command means

  • 1,$: apply the command from the first line to the last line.
  • s: run a substitution.
  • ^: match the start of each line.
  • # or ##: insert the comment marker.
  • g: apply the replacement globally on each matched line.

For shell scripts and many configuration files, # is the usual comment marker. For other file types, use the comment style expected by that format.

Leave a Comment