Home
Effective Commands to Remove Lines in Vim for Every Scenario
Vim is widely recognized for its steep learning curve, but once mastered, its efficiency in text manipulation is unparalleled. One of the most common tasks any developer or system administrator performs is removing lines of text. Whether you are cleaning up a configuration file, stripping comments from source code, or managing massive log files, knowing the right command can save minutes of tedious manual labor.
To remove the current line in Vim, the fastest method is to press Esc to enter Normal mode and type dd. This immediate action deletes the line and stores it in the default register.
However, Vim offers a vast array of specialized commands for more complex deletion tasks. This article explores the various methods to remove lines, ranging from basic keystrokes to advanced pattern-based batch processing.
Understanding the Logic of Deletion in Vim
Before diving into specific commands, it is essential to understand that in Vim, "deleting" is often synonymous with "cutting." When you delete a line, Vim moves that text into a register (a temporary storage area similar to a clipboard). This design allows you to "put" (paste) the deleted text elsewhere using the p or P keys.
Furthermore, deletion commands change depending on the mode you are in. Most basic deletions happen in Normal Mode, while bulk operations or range-based deletions utilize Command-Line Mode (also known as Ex mode).
Basic Line Deletion in Normal Mode
Normal mode is where you spend most of your time in Vim. It is optimized for navigation and manipulation rather than typing.
Deleting a Single Line
The most fundamental command is dd. When you type this while the cursor is on any line, that entire line disappears.
- Press
Escto ensure you are in Normal Mode. - Move your cursor to the target line.
- Type
ddquickly.
In our practical tests, the dd command is the fastest way to handle ad-hoc edits. It doesn't require hitting Enter, making it an instantaneous operation.
Deleting Multiple Consecutive Lines
If you need to remove a block of text, you can use a "count" prefix with the dd command. The syntax is [number]dd.
For example, typing 5dd will delete the current line and the four lines immediately below it, totaling five lines. This is incredibly useful when you know exactly how many lines of boilerplate code or header information you need to discard.
Deleting to the End of the File
Sometimes you want to keep the beginning of a file but remove everything from your current position to the very bottom. Instead of calculating line numbers, use the combination of the delete operator and the "End of File" motion:
- Command:
dG
Conversely, if you want to delete everything from the current line up to the start of the file, use:
- Command:
dgg
Using Visual Mode for Precise Selection
While counts (like 10dd) are efficient, they require you to count lines, which can lead to errors in large files. Visual Mode provides a graphical way to see exactly what you are deleting.
Visual Line Mode
- Press
V(uppercase) to enter Visual Line Mode. - Use navigation keys (
jfor down,kfor up, or arrow keys) to highlight the lines. - Once the desired block is highlighted, press
dto delete it.
From an experiential standpoint, Visual Mode is the "safety first" approach. In our workflow, we prefer using V when working on sensitive configuration files where a single accidental deletion could break a service. The visual feedback ensures no "off-by-one" errors occur.
Advanced Deletion with Command Mode
When dealing with specific line numbers or large ranges, entering Command-Line mode by typing : is the superior choice.
Deleting Specific Line Numbers
If you know you want to remove line 42, you don't need to navigate there. Simply type:
:42d
To delete a range, such as lines 10 through 25, use the comma separator:
:10,25d
Using Special Symbols in Ranges
Command mode supports several symbols that represent positions in the file:
.(Dot): Represents the current line.$: Represents the last line of the file.%: Represents the entire file.
Examples of these in action:
:. , $d: Delete from the current line to the end of the file.:1 , .d: Delete from the start of the file to the current line.:%d: Delete every single line in the file (clear the buffer).
Pattern Based Deletion Using the Global Command
This is where Vim truly outperforms modern GUI editors. The :g (global) command allows you to execute a deletion on every line that matches a specific search pattern or regular expression.
The Basic Global Syntax
The syntax follows the structure :g/pattern/d.
-
Delete lines containing a word: To remove every line that contains the word "ERROR", run:
:g/ERROR/d -
Inverted Deletion: To delete every line that does not contain a word, use
:vor:g!::v/KEEP/dThis is extremely powerful for filtering logs to find only relevant entries.
Deleting Blank and Whitespace Lines
Empty lines often clutter code. You can remove them using regex:
- Strictly empty lines:
:g/^$/d - Lines containing only spaces or tabs:
:g/^\s*$/d
In our experience managing legacy codebases, running :g/^\s*$/d is one of the first steps in refactoring, as it standardizes the file structure immediately.
Deleting Comments
In scripts like Bash or Python, comments usually start with a #. To remove all lines starting with a comment:
:g/^\s*#/d
This pattern accounts for indentation (the \s* part), ensuring that even indented comments are caught and removed.
Managing the Delete Buffer with Registers
As mentioned earlier, Vim's dd is technically a cut operation. This can be annoying if you already have something in your clipboard that you want to paste, but you need to delete a line first.
The Black Hole Register
To delete a line permanently without affecting your current paste buffer, use the "black hole" register, symbolized by _.
- Command:
"_dd
By prefixing the deletion with "_, you tell Vim to throw the data away rather than storing it. This is a pro-tip for maintaining a clean workflow during complex copy-paste operations.
Using Named Registers
If you want to delete several different lines and keep them in different "clipboards," you can use named registers a through z.
- Command:
"add(Deletes the line into register 'a') - Command:
"bdd(Deletes another line into register 'b')
You can later paste them using "ap or "bp.
Practical Workflow Comparisons
| Requirement | Preferred Method | Why? |
|---|---|---|
| Delete 1-2 lines | dd |
Fastest keystroke. |
| Delete 5-10 lines | V + d |
Visual confirmation prevents mistakes. |
| Delete lines 100-500 | :100,500d |
Faster than scrolling. |
| Filter logs | :g/pattern/d |
Batch processing capability. |
| Clear entire file | :%d |
Standard Ex command for clearing buffers. |
Undoing Mistakes
Vim provides a robust undo system. If you delete something by accident:
- Press
uin Normal mode to undo the last action. - Press
Ctrl + rto redo if you accidentally undid too much.
Unlike many editors, Vim tracks changes in a tree-like structure. Even if you delete lines, type new text, and then realize you need the old lines back, you can often navigate back to that state.
Efficiency Hacks for Power Users
Deleting within a Line
While the query focuses on removing whole lines, often you need to remove everything from the cursor to the end of the line.
- Command:
D(ord$) - Command:
d0(Deletes from cursor to the start of the line)
Using Search and Delete
You can combine the delete operator with a search motion. If you want to delete everything from your current position until the next occurrence of the word "Conclusion":
- Command:
d/Conclusion
Vim will search for the word and delete the text in between.
Macros for Repetitive Deletion
If you have a complex deletion task that isn't easily solved with a regex, you can record a macro.
- Press
qqto start recording in registerq. - Perform your deletion (e.g., move down three lines, delete one, move to the end of the word).
- Press
qto stop recording. - Press
@qto replay the action, or100@qto replay it 100 times.
Summary
Mastering line removal in Vim is about choosing the right tool for the specific scale of the task. For quick edits, dd is unbeatable. For structural changes, the :g command provides programmatic power. By integrating these commands into your daily workflow, you reduce the friction of text editing and move closer to the "speed of thought" editing that Vim is famous for.
Frequently Asked Questions
What is the difference between d and dd?
In Vim, d is an operator that requires a motion to tell it what to delete (e.g., dw for word, d$ for end of line). dd is a shorthand command that specifically targets the entire current line.
Can I delete lines in Vim without entering Normal Mode?
While most deletions happen in Normal or Command mode, you can use Ctrl + u in Insert mode to delete everything from the cursor back to the start of the line. However, for full line deletion, switching to Normal mode is standard practice.
How do I delete lines containing a specific pattern only within a certain range?
You can combine a range with the global command. For example, to delete lines containing "DEBUG" only between lines 50 and 100, use:
:50,100g/DEBUG/d
Does deleting lines in Vim work the same as in Vi?
Yes, most basic line deletion commands like dd, :d, and :g are part of the original Vi specification and work identically in Vim and Neovim.
How can I remove all empty lines including those with spaces?
Use the command :g/^\s*$/d. The ^ marks the start, \s* matches zero or more whitespace characters, and $ marks the end of the line.
-
Topic: How to Delete Lines in Vim / Vi | Linuxizehttps://linuxize.com/post/vim-delete-line/#:~:text=of%20the%20file-,Deleting%20All%20Lines,%3A%25d%20and%20press%20Enter.
-
Topic: How to Delete Lines in Vim / Vi: A Comprehensive Guide — linuxvox.comhttps://linuxvox.com/blog/how-to-delete-lines-in-vim-vi/
-
Topic: How to Delete Multiple Lines in Vimhttps://linuxhandbook.com/delete-multiple-lines-vim/