vim vi – How to Comment Out Multiple Lines of Code by Line Numbers Using vi or vim

vivim

I have learned from this Stack Overflow question that it is possible to use vi/vim to comment out a specified range of line numbers. For example, suppose I have the following bash script:

#!/bin/bash

This
is
my
very
very
great
script

Now suppose that I want to comment out line numbers 6 through 8 (which contain the words very, very, and great) using the # comment character. In vi/vim, I can simply type :6,8s/^/# to obtain the following:

#!/bin/bash

This
is
my
#very
#very
#great
script

which comments out lines 6 through 8.

My question is, is it possible to type a similar one liner that will remove the # comment character from lines 6 through 8 (but not any other commented lines in the file)?

Having said this, I realize that there is some debate about whether I am actually using vi or vim. In practice, I open a file script.sh with the command vi script.sh. Also, when I type the command which vi, I obtain /usr/bin/vi. Nevertheless, when I simply type vi and press Enter, I obtain this:

~                              VIM - Vi IMproved
~
~                               version 7.2.330
~                           by Bram Moolenaar et al.
~                 Vim is open source and freely distributable
~
~                           Sponsor Vim development!
~                type  :help sponsor<Enter>    for information
~
~                type  :q<Enter>               to exit
~                type  :help<Enter>  or  <F1>  for on-line help
~                type  :help version7<Enter>   for version info

which seems to suggest that I'm actually using vim. I am accessing a remote Ubuntu Linux cluster using SSH from my PC. I am not using a Ubuntu Linux GUI.

Best Answer

You can use:

:6,8s/^#//

But much easier is to use Block Visual selection mode: Go to beginning of line 6, press Ctrl-v, go down to line 8 and press x.

There is also "The NERD Commenter" plugin.

Related Question