How to clear text that existed in a text file with out opening it ?
I mean for example I have a file as hello.txt with some text data in it & how can I clear the total text in that file with out opening it.
I am also going to use redirection like rajagenupula's answer. But there is a little more flexibility. Open a terminal and type,
cat > hello.txt
And press Ctrl+C. It will wipe out the previous file. If you want upto this much it is fine.
If you wish you can do something more after wiping the file. In this way not only you can wipe a file without opening but also you can write a few lines with proper formatting in the file. Say you wish to write "Ubuntu is the best OS" after wiping the file, just do
cat > hello.txt Ubuntu is the best OS
Then press Ctrl+C. Now the previous file is wiped out. At the same time words are there in two lines as I put them.
See the example:
I have to do this all the time with log files. The easiest way I have found is with the following command:
cat /dev/null > hello.txt
This deletes allo of the content of the file, and leaves you with an empty file without having to open it in an editor, select text, any of that stuff. More specifically what it does is to replace the contents of the file with the contents of "/dev/null", or nothing. It's pretty slick, actually.
The only caveat is that the user you are currently logged in as must have write permission to said file.
Another approach -
/dev/null to the file
xieerqi:$ cat testFile.txt Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda1 115247656 83100492 26269816 76% / none 4 0 4 0% /sys/fs/cgroup udev 2914492 4 2914488 1% /dev tmpfs 585216 1152 584064 1% /run none 5120 0 5120 0% /run/lock none 2926072 98096 2827976 4% /run/shm none 102400 76 102324 1% /run/user xieerqi:$ cp /dev/null testFile.txt xieerqi:$ cat testFile.txt xieerqi:$
This answer is based on another from Super User. Although not the shortest bash command,
truncate is the most readable for average newbies:
$ echo Hello > Hello.txt $ echo World! >> Hello.txt $ cat Hello.txt Hello World! $ truncate -s 0 Hello.txt $ ll Hello.txt -rw-rw-r-- 1 rick rick 0 Mar 20 17:32 Hello.txt
Parameters used with
truncate command here:
An advantage of
truncate is you can specify how much to keep, not just zero:
$ truncate -s 10000 Hello.txt
... will truncate everything after the first 10,000 bytes. This could be useful if a program went crazy and dumped many Megabytes of data into a small log file:
truncatecommand for a reasonable larger normal size of 10K
So, I see a lot of redirections being used to answer this ;)
A little different approach with the combo: rm & touch
rm hello.txt && touch hello.txt
(yeah... yet another cheat!)
So with this command combo the file hello.txt wasn't opened and in the end you still have file hello.txt in its place with the contents cleared. Just like you wanted!