Deleting a file in Unix/Linux is as simple as issuing the rm command. But here, we present some methods that will clear/empty a file in Linux rather than deleting it. It means that the contents of the file will be removed and not the file itself.
In the following methods, we assume that the name of the file to be removed is “raghu.txt” and it is present in your current working directory.
1) Using ‘cp’ (copy) command
‘/dev/null’ is a special file that contains nothing. Whatever you put in this file, it disappears forever. It is like a black hole, whatever goes in never comes out. This command copies ‘/dev/null’ to the file to be emptied.
$ cp /dev/null raghu.txt
2) Using ‘dd’ command
The dd command copies raw files in the form of bytes. Two files are supplied to the ‘dd’ command, an input file, given by if=/dev/null and an output file, of=raghu.txt. The bs=1 value represents the block size (this cannot be 0) and count=0 is the number count (0 here) of blocks, i.e. how many blocks (of size given by ‘bs’) must be copied.
$ dd if=/dev/null of=raghu.txt bs=1 count=0
3) Redirection method
The following commands use redirection for removing the contents of the file.
$ > raghu.txt
4) Using echo command
You can use below echo command to empty file contents
$ echo -n "" >raghu.txt
5) Using "cat" command
The following cat command puts the contents of the file ‘/dev/null’ in raghu.txt
$ cat /dev/null >raghu.txt
$ cat > raghu.txt
And then press ctrl + d.
In this method, the cat command puts everything you type afterwards in the file raghu.txt, until ‘ctrl+d’ id pressed. So here, we do not write anything to file and directly press ‘ctrl+d’ so that "nothing" goes in the file.
You can also use other tools like ‘sed’ or ‘awk’ with redirection to remove file contents.
6) Using vi editor
And finally, using a text editor like ‘vi’. This is the most obvious method
Open the file in ‘vi’ editor (or any other editor).
$ vi raghu.txt
And then press ‘99999dd’. This will delete at most 99999 lines from the file. If you believe that your file can have more than 99999 lines, you can precede “dd” with a number greater than the number of lines in your file. Now save the file and quit from the editor using “:wq”.
If you are using some other advanced editor like “gedit”, then you can press ‘ctrl+a’ to select all the text in the file and then press backspace or delete key to remove the text. Now, save the file and exit from your editor.