Open In App

How to Comment and Uncomment multiple line vi terminal editor

Last Updated : 02 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Introduction

The Vi and Vim text editors are renowned for their efficiency in handling various text-editing tasks. One such task that often comes up in programming and text manipulation is the need to comment or uncomment multiple lines of code or text. Whether you’re annotating sections of your code for clarity or removing comments to activate specific functionality, Vi/Vim provides an elegant solution for these tasks.

In this article, we will go through the step-by-step process of both commenting and uncommenting multiple lines within Vi/Vim editors.

Commenting Multiple Lines

Steps:

1. Open the File: Open the file you wish to edit in vi/vim. You can do this by entering the following command in your terminal, replacing ‘filename’ with the name of your file.

vi filename

2. Navigate to the beginning of the block: Use the vi movement commands or arrow keys to position the cursor at the start of the lines you like to comment.

3. Enter Visual mode: Press ‘Shift + V(uppercase V). This mode enables you to select multiple lines of text. Use arrow keys to select the lines you want to comment.

4. Commenting the lines: In Visual mode, enter command-line mode by pressing ‘:’ (colon). Now, type ‘s/^/#’ and press Enter. This command employs regular expressions to prepend a ‘#’ character to the beginning of each selected line.

5. After successfully commenting the lines, press ‘Esc’ to exit Visual mode. If you wish to save your changes and quit, type ‘:wq’ and press ‘Enter’.

Comment

Uncommenting Multiple Lines

Steps:

1. Open the File: Open the file in Vi/Vim editor and follow the same procedure mentioned earlier.

2. Navigate to the beginning of the block: Position the cursor at the start of the lines you intend to uncomment.

3. Enter Visual mode: Activate visual mode with ‘Shift+V’ and select the lines to be uncommented by using the arrow keys.

4. Uncommenting the Lines: Enter command-line mode with ‘:’ and type ‘s/^#//’, then press ‘Enter’. This command will remove the ‘#’ character from the beginning of each selected line.

5. Exit Visual mode by pressing ‘Esc’. If you wish to save your changes and quit, press ‘:wq’ and press ‘Enter’.

Uncomment

Uncommenting Lines

Conclusion:

In conclusion, learning how to comment and uncomment multiple lines in Vi/Vim is a valuable skill for anyone working with text-based content. Whether you’re a programmer or a writer, these techniques can help you annotate code for clarity or activate/deactivate specific sections quickly.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads