How to Delete Lines in Vim and Vi

Vim and Vi are popular text editors often used in Unix-based systems. Vi is the original, lightweight editor found on nearly all Unix systems, while Vim (Vi Improved) is its more advanced version, packed with features like syntax highlighting, undo/redo, and more. Both are widely appreciated by developers and system administrators for their speed and efficiency, though they can feel tricky for beginners.  

Knowing how to delete lines in Vim editor or Vi editor is a handy skill, especially when working with large files or making quick edits in a terminal. You might need to remove outdated code, clean up configuration files, or tidy logs for better readability. While the commands are simple, mastering them makes navigating and editing text a lot faster, saving time and avoiding the frustration of guesswork.  

In this article, we will show you how to delete lines in Vim and Vi with clear easy-to-follow steps.

Installing Vi/Vim on Linux

Before using Vi or Vim for editing tasks like deleting lines, it’s important to ensure they are installed and working properly. The good news is that installing Vim will also install Vi automatically, as Vim is an enhanced version of Vi.  

Use the following commands to install Vim on your Debian-based Linux distribution: 

sudo apt install vim -y
install vim y

In case you are using RHEL-based distribution, you can use the below two commands:

sudo yum install vim -y
sudo dnf install vim -y 

After installing, check if Vim (and Vi) was installed correctly by running:

vi --version
vi version

If the command displays version details, everything is set up and ready to use. With Vim installed, you can start editing files and perform tasks like deleting lines efficiently.

Moreover, the output also shows that the installation is compatible with both Vi and Vim.

Deleting Lines in Vi/Vim

Deleting lines in Vi and Vim is simple once you understand the commands. Both editors provide multiple ways to handle deletions, depending on whether you need to remove a single line, multiple lines, or lines matching a specific pattern. Here’s how you can use these commands effectively.

Deleting a Single Line

First, ensure you are in normal mode by pressing Esc. Move the cursor to the line you want to delete. To remove that line, type:

dd 
linux os

This command deletes the entire line where the cursor is positioned. The d stands for “delete,” and repeating it (dd) indicates you want to delete the current line.

As you can see the cursor is on Line 1 so when you press dd here, it will delete Line 1:

vi/vim

Deleting Multiple Lines

If you want to delete multiple lines starting from the current cursor position, you can use the syntax ndd. Replace n with the number of lines you wish to delete. For example:

3dd
kernel

Here, 3 specifies that three lines will be deleted, including the line where the cursor is positioned and the next two lines:

Delete a Range of Lines

To delete a specific range of lines, switch to command mode by typing: and then specify the range followed by d. For instance:

:5,10d 
range delete

This deletes lines 5 through 10 in the file. The range 5,10 tells Vim which lines to target, and the d command deletes them:

linux

Deleting Lines to the End of the File

To delete all lines from the current line to the end of the file, use:

dG
lines delete

Here, d stands for delete, and G moves the cursor to the last line of the file, deleting everything in between. As the cursor is on line 3, so it removes all lines including line 3 and the below ones when you press dG:

command line

Deleting Lines to the Beginning of the File

To delete all lines from the current line back to the beginning of the file, use:

dgg
bash linux

In this case, gg moves the cursor to the start of the file, and the d command deletes everything between the cursor’s starting position and the top:

SElinux

Deleting Lines Containing Specific Patterns

To delete lines that contain a specific pattern, enter command mode by typing: and use the syntax:

:g/pattern/d

Replace the pattern with the text you want to match. For example, to delete all lines containing the word “error,” you would type:

:g/Linux/d
g/linux/d

The g stands for global, meaning it will search the entire file for the specified pattern. So when we execute the command it deletes all the lines having Linux in it:

fewer lines

Delete Lines Not Matching a Pattern

To delete lines that do not contain a pattern, use:

:v/Linux/d
lines delete

Best Practices for Deleting Lines in Vi/Vim

While deleting lines in Vi or Vim is straightforward, following a few best practices can make your workflow more efficient and reduce the risk of accidental changes. Before digging into the best practices of deleting a line in Vi/Vim you need to understand how to find and replace in Vim and Vi. Here are some key tips to keep in mind:

Ensure You Are in the Correct Mode

Vi and Vim operate in different modes, and commands behave differently depending on the mode you are in. Always press Esc before executing any line deletion commands to ensure you are in normal mode. This avoids unintended actions caused by being in insert or visual mode.

Preview Before You Delete

When deleting a range of lines or lines matching a pattern, preview the changes to ensure accuracy. Instead of directly using `:g/pattern/d`, start with :g/pattern/.

This highlights all matching lines without deleting them. Once you confirm the selection, you can safely use the deletion command.

Use Undo (u) and Redo (Ctrl+r)

Accidental deletions happen, but Vim undo (`u`) and redo (`Ctrl+r`) commands are your safety net. Always verify changes after a deletion, and if something goes wrong, use `u` to revert or Ctrl+r to redo.

Save Your Work Regularly

If you’re working on a large file and performing multiple deletions, save your changes periodically using the `:w` command. This ensures you don’t lose progress if something unexpected happens.  

Be Specific with Ranges

When using commands like `:5,10d`, double-check the range before executing. Use `:set number` to display line numbers in the editor, making it easier to define precise ranges.

Backup the File

For critical files, it’s a good idea to create a backup before performing bulk deletions. You can duplicate the file directly from the terminal by executing the cp original_file.txt backup_file.txt command. This allows you to revert to the original version if needed.

Use Visual Mode for Precision

If you’re unsure about specific line numbers, use visual mode to highlight the lines you want to delete. Press V in normal mode to enter line-wise visual mode, then use the arrow keys to select lines and press d to delete them.

Avoid Unintentional Global Deletions

Global commands like :g/pattern/d can have a big impact on your file. Always double-check your pattern to ensure it targets the intended lines. Mistakes in global commands can lead to losing significant portions of your content.

Test Commands on Non-Critical Files

If you’re new to Vi or Vim or testing unfamiliar commands, practice on a non-critical file. Create a temporary file using touch test_file.txt command. Experimenting in a safe environment helps you learn without the risk of damaging important files.  

By following these best practices, you can delete lines in Vi and Vim confidently and avoid common mistakes.

Conclusion

Deleting lines in Vi and Vim may seem challenging at first, but with practice, it becomes an efficient way to edit files. From removing a single line to targeting specific patterns, these editors provide flexible commands that can handle various scenarios. Understanding and applying these commands correctly ensures that you maintain precision and avoid unnecessary deletions.

By mastering the commands discussed in the article, you can easily manage even large files with complex edits. Combined with best practices such as previewing matches and using undo, you’ll gain confidence in handling any deletion task. Vim and Vi remain powerful tools for file editing, and their robust command set makes them indispensable for developers and system administrators.

Mastering the editing function in Vim and Vi can greatly improve your text editing efficiency. For a seamless experience, try Ultahost’s fast VPS hosting. With affordable plans, Ultahost provides the perfect environment to use Vim and Vi editor without interruptions.

FAQ

How do I delete a single line in Vim?
Can I undo a deleted line in Vim?
How do I delete multiple lines in Vim?
What happens if I use dG in Vim?
How can I delete lines matching a specific pattern in Vim?
Is there a way to preview lines before deleting them in Vim?
Can I delete lines in Vim without opening the file?

Related Post

How to Install Rancher on CentOS 7

Rancher is an open-source platform that simplifies the ...

How to Check Disk Free Space on Linux

Checking and managing free space on your system disk is...

How to Install Plesk on Linux

Plesk is a comprehensive web hosting control panel desi...

What is the Load Average in Linux? How to Che

The Load Average which is also known as system load is ...

Creating and Managing Files in Linux

Linux is a family of open-source Unix-like operating sy...

How to Use the which Command in Linux

The which command in Linux is a simple yet powerful uti...

Leave a Comment