MQ-Jr
MQ-Jr
unixcop Admin

How to comment multiple lines at once in vim editor using 3 methods

Introduction

Vim is an excellent command-line text editor, especially if you are comfortable with its shortcuts, modes, and bindings. However, when working with it.

We can encounter instances where we need to comment on code blocks while editing code and configuration files.


This article describes quick and easy ways to comment out multiple lines of code in Vim editor.

Method (1):

  • Open the file using vim editor
vim unixcop.txt
  • Highlight the lines that you want to comment out by going to the line you want to comment and press SHIFT+V then move the cursor up or down keys or k or j according to your cursor position to highlight lines one by one as shown below.
  • Type the following and press ENTER
:s/^/# /

s: stands for substitution.

So we substitute the caret symbol  (^) (in the beginning of the line) with (#) (hash).

  • You will see the selected lines are commented then type :wq to save the file and exit.

Method (2):

  • Open the file with vim
vim unixcop.txt
  • Set line numbers by typing the below then press ENTER.
:set number
  • Enter the following command then press ENTER.
:1,7s/^/#

Replace (7) with the number of lines you want to hash.

  •  Unset the line numbers.
:set nonumber
  • Type :wq to save the file and exit.

Method (3):

  • Open the file with vim
  • vim lines.txt
    • Type the following and press ENTER key:
    :g/\line/s/^/# /

    The above command will comment out all lines that contains the word line.

    Replace line with a word of your choice.

    Conclusion

    That’s it

    In this article, we showed you how to comment multiple lines at once in vim editor using 3 methods.

    Thanks

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here

    Latest articles

    Join us on Facebook

    x