Site icon DesignLinux

How to Delete Lines in Vim / Vi

Vim or its precursor Vi comes preinstalled on most Linux distributions and macOS. Knowing the basics of Vim is important if you are a system administrator or just a regular Linux user.

Quite often, when working with text files, you’ll need to delete one or more lines.

This article shows how to delete lines in Vim/Vi.

Deleting a Line

The command to delete a line in Vim is dd.

Below are step-by-step instructions to delete a line:

  1. Press the Esc key to go to normal mode.
  2. Place the cursor on the line you want to delete.
  3. Type dd and hit Enter to remove the line.

Pressing dd multiple times will delete multiple lines.

Deleting Multiple Lines

To delete multiple lines at once, prepend the dd command with the number of lines to be deleted. For example, to delete five lines you would do the following:

  1. Press the Esc key to go to normal mode.
  2. Place the cursor on the first line you want to delete.
  3. Type 5dd and hit Enter to delete the next five lines.

Delete a range of lines

The syntax for deleting a range of lines is as follows:

:[start],[end]d

For example, to delete lines starting from 3 to 5 you would do the following:

  1. Press the Esc key to go to normal mode.
  2. Type :3,5d and hit Enter to delete the lines.

You can also use the following characters to specify the range:

Here are a few examples:

Delete All Lines

To delete all line you can use either the % symbol that represents all lines or the 1,$ range:

  1. Press the Esc key to go to normal mode.
  2. Type %d and hit Enter to delete all the lines.

Deleting Lines Containing a Pattern

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

:g/<pattern>/d

The global command (g) tells the delete command (d) to delete all lines containing the <pattern>.

To match the lines not matching the pattern, add an exclamation mark (!) before the pattern:

:g!/<pattern>/d

The pattern can be a literal match or regular expression . Below are some examples:

Conclusion

We have shown you how to delete lines in Vim.

If you are new to Vim, visit the Open Vim site where you can practice Vim with an interactive tutorial.

Feel free to leave a comment if you have any questions.

terminal vim
Exit mobile version