Commenting out multiple lines of code, specified by line numbers, using vi or vim

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.


I know your question specifies using vi or vim but here are a few other options for doing this without having to manually open the file:

  • Perl

    perl -ne 'if($. <=8 && $. >= 6){s/^\s*#//;}print' foo.sh 
    
  • Perl version >=5.10

    perl -ne '$. ~~ [6..8] && s/^\s*#//;print' foo.sh 
    

    This will print out the contents of the file, you can either redirect to another (> new_file.sh) or use i to edit the file in place:

    perl -i -ne '$. ~~ [6..8] && s/^\s*#//;print' foo.sh 
    
  • sed

    sed '6,8 s/^ *#//' foo.sh
    

    Again, to make this edit the original file in place, use i:

    sed -i '6,8 s/^ *#//' foo.sh
    
  • awk/gawk etc:

    gawk '(NR<=8 && NR>= 6){sub("^ *#","")}{print}' foo.sh
    
  • Pure bash:

    c=1; while read line; do 
      if [ $c -ge 6 ] && [ $c -le 8 ]; then 
         echo "${line/\#/}"
      else 
         echo $line 
      fi
      let c++; done < foo.sh
    

vi is a symbolic link to vim in most GNU/Linux distribution so you're indeed using vim when you type vi.

To remove the comments, you can type: :6,8s/^#// or :6,8s/^\s*#// to discard some leading space before the # symbol.

Tags:

Vi

Vim