7 Examples To Delete/Erase Contents Of File In Linux But Not File

May 23, 2011 | By
| Reply More

Deleting a file in Unix/Linux is as simple as issuing the “rm” command (with file name as an argument). But here, we present some methods that will empty your file 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

$ cp /dev/null raghu.txt

‘/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.

2. Using ‘dd’ command

$ dd if=/dev/null of=raghu.txt bs=1 count=0

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.

The following commands use redirection for removing the contents of the file.

3. This is the simplest one

$ > raghu.txt

4. Using echo command

$ echo -n "" >raghu.txt

5. The following command puts the contents of the file ‘/dev/null’ in raghu.txt

$ cat /dev/null >raghu.txt

6. This is another method using cat command

$ 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.

7. And finally, using a text editor like ‘vi’. This is 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.


Free Linux Ebook to Download

Leave a Reply

Commenting Policy:
Promotion of your products ? Comment gets deleted.
All comments are subject to moderation.