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


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.

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.


    That’s it

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


    unixcop Admin


    Please enter your comment!
    Please enter your name here

    Latest articles

    You might also likeRELATED

    How to set PassivePortRange and PassiveIP in pure-ftpd on Ubuntu to secure the app!

    Introduction Hi guys, We will talk about setting PassivePortRange and PassiveIP in pure-ftpd. If you run a firewall on your Linux server and want to...

    Install Java 8 on CentOS 8

    Hi Guys, In this guide, we’ll show you how to install Oracle’s Java 8 programming language on CentOS 8 . It's an object-oriented language...

    How to install flameshot on RHEL/CentOS using Snapcraft

    In this post, you will learn how to install Flameshot on RHEL / CentOS Flameshot is a powerful open source screenshot and annotation tool for...