Vi Editor is one of the most popular file editors in Linux. It is widely used by software developers, coders as well as document editors. Often we may need to delete all text in a file while using vi editor. It can be tedious to manually delete all lines if it is a large file with many lines of content. In this article, we will learn how to quickly delete all text in file using vi editor.
How to Delete All Text in File Using Vi Editor
Vim editor offers different modes (normal, insert & command) to work with files. We will learn how to delete all text in file in each of these modes.
Delete All Text in File in Normal Mode
Let us say you have opened the following file in vi editor.
$ vi data.txt
Immediately after opening the file type gg to move cursor to the first line of the file. Then simply type dG (G uppercase) to delete all lines or text in it.
Delete All Text in File in Insert Mode
If you are in insert mode, then press Esc or <C-[> to go to normal mode. Once you are in normal mode, you can use the above step to delete all lines in your file.
Delete All Text in File in Command Mode
If you are in command mode (press Esc in insert mode to go to command mode), you can also enter the following command and press Enter to delete all lines of your file.
In this short article, we have learnt how to remove all lines in file using vi editor. This is a requirement faced by many beginners as well as experienced vi users. Please note, if your file is really large it may take some time for vi editor to remove all the lines in it.
Alternatively, you can exit vi editor and empty your file from terminal using cat. Here are some of the simple ways to easily clear large files in Linux.
# > /path/to/file # true > /path/to/file # : > /path/to/file # sudo cat /dev/null > /path/to/file # sudo cp /dev/null > /path/to/file # sudo echo '' > /path/to/file # sudo echo > /path/to/file # sudo truncate -s 0 /path/to/file
How to Edit Hex Files in Linux
How to Add/Remove Software Repository in Fedora
How to Password Protect Vim File in Linux
How to Check Linux Server Location
How to Encrypt Drives Using LUKS in Linux