Comment uncomment and replace characters in multiple lines in Vim


Modifying files in Vim can be arduous and time-consuming, especially when we want to modify multiple lines at once. The typical use case is modifying a configuration file in the system when it is required to comment or uncomment multiple lines at a time, or to replace the same character in many similar lines from the top to the bottom. Here are a few hints on how to facilitate multiple line modifications in text files using Vim editor.

 

How to comment multiple lines at once in Vim

Move the cursor to the first character of the first line in the block code that you want to comment, then type Ctrl + v, to enter into VISUAL BLOCK mode.

Use the arrow key to move the cursor down until you reach the last line of your code block, that you want to comment:

This will mark all the lines, from the top to bottom, which you are going to comment out.

Now type Shift + i, to enter into INSERT mode and the cursor will go back up to the first from the marked lines:

Next, type # (hash) sign at the beginning of the first line:

Now, press Esc and the # (hash) sign will appear at the beginning of each line from the previously marked block:

The whole code block is now commented.

 

How to uncomment multiple lines at a time in Vim

Move the cursor to the first character of the first commented line in the block code that you want to uncomment, then type Ctrl + v, to enter into VISUAL BLOCK mode.

Use the arrow key to move the cursor down until you reach the last line of your code block, that you want to uncomment:

Now press the Delete key to remove # (hash) character from each line in the marked block:

The whole code block is now uncommented.

 

Replace a character in a particular column across multiple rows in Vim

Move the cursor to the first row, to the character, which you want to replace with the new one, then type Ctrl + v, to enter into VISUAL BLOCK mode.

Use the arrow key to move the cursor down until you reach the last line of your code block, that you want to modify:

Now press the R key to replace the whole column, next type the new character, you want to replace the whole column with, i. e. the x key:

The whole column has been replaced with a new character across all marked rows.