Comment a block of code in vi

Having to comment a block of code in a script and/or program can suck if you do it the wrong way. Yes, I am talking about the tedious:

  • SHIFT+3 (gets you the “#” sign)
  • Down Arrow
  • Left Arrow
  • Wash, Rinse and Repeat for as many lines that you wish to comment out.

This can be a daunting task even for the quickest of fingers out there. Many of you might be thinking, “But I only comment a few lines when I have to do it so it really doesn’t bother me to do it the tedious way“. Well, if thats the case then skip this tip since its not for you. Otherwise, if you have to comment 20, 30, or 100+ lines of any file in vi or just want to learn something new, then read on.

This is how you comment in a block of code using vi:

  1. Open any text file using vi
  2. Enter the following code into vi’s command mode:

    :START,ENDs/^/# /

    where START is the starting line number and END is the ending line number.

  3. Thats it!

So if I wanted to comment all the lines starting from 10 through 30 in my test file, I would use:

:10,30s/^/# /

This will comment lines 10 through line 30 of the current buffer (file). This same principle can be used for indentation and/or un-commenting said file. Obviously, just replace ^ and # with the appropriate entries. I know what you are thinking, “This is cool and all but how do I get the exact line numbers to comment?” Well, check out my “vi notes” from a previous posting under the “vi Options”. (HINT: :set nu) While you are there, check out the rest of the vi tips. I’m sure you will learn something, ;). Have fun vi’ing!

About this entry