Vim is a popular command-line text editor that’s present on most Linux distros and macOS. Knowing how to use the editor can save you a lot of time when jumping about the terminal.
In this article, we’re taking a look at how you can delete lines in Vim through the following four guides.
- Deleting a single line in Vim
- Deleting multiple lines in Vim
- Deleting a range of lines in Vim
- Deleting lines with a pattern on Vim
How to delete a line in Vim?
Step 1: Press Esc to go to Normal mode and place the cursor on the line you want to delete.
Step 2: Type dd to delete the line. Note that pressing dd multiple times will delete multiple lines.
Also read: Mint vs Ubuntu: Linux distro comparison
How to delete multiple lines in Vim?
You can prefix the number of lines you want to delete to the dd command to remove multiple lines at once.
Step 1: Press Esc to go to Normal mode and place the cursor on the line you want to delete.
Step 2: Type 3dd and hit enter to delete three lines from the cursor’s position. You can replace the number with the number of lines you want to delete.
Also read: How to open task manager in Linux?
How to delete a range of lines in Vim?
Use this syntax to remove a range of lines at the same time.
:[start], [end]d
Step 1: Press Esc to go to Normal mode.
Step 2: Enter :4,10d to delete line 4 to 10. You can change these numbers as per your requirement.
Here are a few characters you can use to specify ranges.
- . : Deletes the current line.
- $: Removes the last line.
- %: Removes all lines.
For example, to delete all lines in a document, you’d simply use $d.
How to delete lines with a pattern in Vim?
Use the d command in the following syntax to delete lines with a pattern.
:g/<pattern>/d
The syntax involves the global command (g) telling the delete command (d) to remove all lines including the <pattern>.
:g!/<pattern>/d
You can add an exclamation mark after the global command to only delete lines not matching the pattern. You can also specify expressions as a pattern. For example.
- :g/del/d: This command will delete all lines containing ‘del’, even if it’s embedded in larger words such as ‘delete’.
- :g!/del/d: Does the exact opposite of the aforementioned command. Deletes all lines that don’t contain ‘del’.
- :g/^$/d: Deletes all blank lines, ^$ being the expression for empty lines.
- :g/^#/d: This command will remove all comments from a bash script as bash comments start with #.
Also read: How to use the Cat command in Linux?