How to Delete all Text Lines in a File Using Vi/Vim in Linux?

Can anyone tell me how to delete all lines in a file? Right now I do the following command to empty a file.

echo > file.txt

But I want to know how can I do the same while I am editing the file with VI
Thanks in advance :slight_smile:

In vi, you can use the following command to delete all lines.

:1,$d
  1. You may already know what : does. It (moves the cursor to the bottom) and allows you to add commands (like save, exit, etc).
  2. 1,$ This part selects the range from line one to the last line. You can define any line here. For example, you can use 5,$-2 which selects from the 5th line to the last 2 lines. This means the first 4 lines and last 2 lines won’t be deleted.
  3. And final d stands for delete.

There is a shorter form for deleting all lines, you can also use this command.

:%d

Hope that helps.