How To Delete Line In Vi/Vim?

Vi or vim provides different commands for operations. One of these operations is deleting the line. Vi or vim provides different commands to delete single or more lines in different ways.

Delete Current Line

The command to delete the current line in Vi/Vim is dd . The current line is the cursor current location. But the dd command should be called in the normal mode which accepts commands. Before issuing the dd command press the ESC key to be sure you are in normal mode.

dd

Pressing the dd command will delete lines in multiple times.

Delete Multiple Lines

The dd command can be also used to delete multiple lines. The number of lines should be specified before the dd command. The delete operation applied after the cursor location. The following command will delete 3 lines after the cursor current location. But before issuing 3dd command press ESC to change to normal mode.

3dd

Delete Specified Lines or Range of Files

The d command can be used to delete multiple lines for the specified range. The range will be specified with the line numbers where the start and end line numbers for deletion will be provided. First, we will change to the command mode with the ESC key. then type the following command in order to delete lines from 12 to 18.

:12,18d

Also following line specifiers can be used to set start and end lines according to the line numbers.

  • . specifies the current line.
  • $ specifies the last line.
  • % specifies all lines.

Take a look to the following examples.

READ  How To Download Files with curl In Linux Command Line?
CommandDescription
:.,20dDelete from the current line to line number 20.
:40,$dDelete from line number 40 to the last line.
:.,$dDelete from the current line to the end of the file.

Delete All Lines

All lines can be deleted by using the % specifier. In this case, you do not need to know the line numbers, the cursor number, etc. Just use the following command where single line number specifier % will be provided.

%d

Leave a Comment