Delete All Lines of a File in Vim
Esc+gg+dG is what you need to do for deleting all the lines of the file in Vim. Here's how it works.
You can delete a line in Vim with dd
i.e. pressing the d
key twice. But what if you want to delete all the lines in Vim?
You cannot do Ctrl+A and use Del key like you do in a regular text editor. That's not how Vim works.
There is no straightforward keyboard shortcut for this. However, you can use the dG
keys if you are at the beginning of the file.
Deleting all lines in Vim
Here are the steps:
- Make sure you are in the command mode in Vim by pressing the
Esc
key. - You need to be at the beginning of the file. Press
gg
for that. This means pressing theg
key in quick succession. - Now press
dG
. This means pressing the keyd
and then holdShift
and pressg
. Yes,G
is uppercase and you'll have to use shift key here the same way you type G.
In short: Esc
+gg
+dG
is what you need to do for deleting all the lines of the file in Vim.
So, how does this dG
command works? To be precise, the d
is for the cut action and G
is for moving the cursor to the end of the file. This way, dG
cuts all the text from the current cursor position to the end of the file.
This is why you need to be at the beginning of the file if you want to delete all the lines in Vim.
There are more ways to empty a file in Linux other than Vim. In case you are interested in that. You can delete the file itself but that's not a very suitable move.
If you are familiar with Vim modes, you can switch to the visual mode and use the arrow keys to select all the text and then delete it. However, this option is also not very convenient.
There are other ways to deal with multiple line deletion in Vim but the focus is on deleting all the lines.
If you are interested in learning more than just the Vim basics, I highly recommend using this program by Jovica Ilic.
Questions or suggestions? Please leave a comment.
Creator of Linux Handbook and It's FOSS. An ardent Linux user & open source promoter. Huge fan of classic detective mysteries from Agatha Christie and Sherlock Holmes to Columbo & Ellery Queen.