Oct 29, 2022 2 min read

How to Delete All Lines of a File in Vim

Table of Contents

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 the g key in quick succession.
  • Now press dG. This means pressing the key d and then hold Shift and press g. 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.

You can undo the delete by pressing the key u. It works for any action you had performed in the command mode 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.

Empty or Truncate a Log File in Linux [4 Ways]
In this tutorial, you’ll learn various ways to truncate a log file and delete its content without deleting the file itself.

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.

Mastering Vim Quickly - Jovica Ilic
Exiting Mastering Vim Quickly From WTF to OMG in no time

Questions or suggestions? Please leave a comment.

Abhishek Prakash
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.
Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to Linux Handbook.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.