Even deleting lines in Vi and Vim can be a nerve-wracking job for newcomers. But using a rudimentary tool like a text editor doesn’t have to be so hard.
Here’s how you can remove one or more lines from a text file using Vi and Vim.
How to Delete a Single Line in Vi/Vim
There’s a better way of deleting complete lines in Vi and Vim than spamming Backspace on the keyboard.
To delete a line in Vi or Vim, switch to normal mode first. If you’re into command mode or insert mode, you can switch back to normal mode by pressing Escape.
Highlight the line that you want to delete, then hit dd or D on the keyboard. The editor will automatically remove the whole line from the file. Note that Vi and Vim commands are case-sensitive, which means d and D are identified as two separate commands.
Hitting dd or D multiple times will delete several lines one by one. The next line will be automatically highlighted once the former is deleted.
Deleting Multiple Lines in Vi and Vim
If you find repeatedly hitting keys on the keyboard inconvenient, you can remove multiple lines at once by tweaking the aforementioned command. Instead of simply pressing dd, you can specify the number of lines you want to delete.
For example, typing 3dd will delete the next three lines from the file.
If you want to delete lines within a specific range, you’ll have to switch to command mode first (press Escape while in normal mode). Then, use the following syntax to create your own deletion command:
For example, to delete the lines between the range one and five:
You can also use wildcard characters in the aforementioned command.
. (Dot): Refers to the current line $ (Dollar): Denotes the end of file % (Percentage): Matches all the lines in the file
For example:
Spamming Backspace? Sorry, I Use Vi/Vim
If you want to become a Linux power user, learning the ins and outs of command-line utilities is the direction you should be heading towards. On Linux, you can use various shortcuts and key bindings to perform tasks that would otherwise take a lot of time and effort.
For those who are looking forward to mastering Vim, there’s good news. The vim package comes with Vimtutor, a free command-line tutor that will help you utilize Vim to its true potential.