vim tutorial: vim delete line

Vim delete lines, as the basic knowledge of vim is one of the functions we must master.

Mastering the skills of deleting lines can improve our efficiency in editing text.

This article will show you how to delete lines in vim.

Delete a Line

The vim delete command is dd.
Yes, it is the cut shortcut mentioned in our previous article. When we only use dd, it can be considered a delete operation.

The steps are as follows:

  1. Open the terminal and use the vim command to open the file.
  2. Move the cursor to the line you want to delete.
  3. Type dd to delete the line.
  4. Save and exit.

Delete multiple lines

If you want to delete multiple non-contiguous lines of the text file, you can move the cursor to the delete line and use dd to delete.

Delete consecutive lines

If you want to delete multiple consecutive lines, we use the following syntax:

3dd

# OR

d3d

The steps are as follows:

  1. Open the terminal and use the vim command to open the file.
  2. Move the cursor to the line you want to delete.
  3. Type d3d to delete 3 lines, including the current line. (Or type 3dd)
  4. Save and exit.

Delete all rows

If we want to delete all lines of the text file, we can use dG or dnd, where n is a number greater than or equal to the total number of lines in the current text.

The steps are as follows:

  1. Open the terminal and use the vim command to open the file.
  2. Move the cursor to the line you want to delete.
  3. Type dG to delete all lines. (Or dnd, n >= total number of rows)
  4. Save and exit.

Delete a range of lines

If you want to delete the range line, we can use the last line command mode, the syntax is as follows:

:[start],[end]d

The steps are as follows:

  1. Open the terminal and use the vim command to open the file.
  2. Move the cursor to the line you want to delete.
  3. Type :2, 4d to delete lines 2 to 4 of the text file.

4. Save and exit.

You can also specify the range using the following characters:

  • . – The current line.
  • $ – The last line.
  • % – All lines.

Here are a few examples:

  • :10,$d – From the 10th line to the end of the file.
  • :%d – Delete all lines.
  • :.,$d – From the current line to the end of the file.

Delete Lines Containing a Pattern

The syntax for deleting multiple lines based on a specific pattern is as follows:

:g/<pattern>/d

  1. Open the terminal and use the vim command to open the file.
  2. Move the cursor to the line you want to delete.
  3. Type :g/vim/d to delete all lines containing vim in the text file.
    • g – stands for global
    • d – delete all lines containing
  4. Save and exit.

In addition, it also contains some special syntax:

  • :g/^$/d – Remove all blank lines.
  • :g!/foo/d – Delete all lines not containing the string “foo”.
  • :g/^foo/d – Delete all lines starting with foo.

Add a Comment

Your email address will not be published.