95

How to clear text that existed in a text file without opening it?

I mean for example I have a file as hello.txt with some text data in it, and how can I clear the total text in that file without opening it?

By this, I mean not using any editor like nano, Gedit, etc.

  • 1
    What do you mean by 'opening' a file? In all the answers given so far the file will still be opened for writing by the shell. In the end the shell is just a program like any other. – Jeff Dec 13 '13 at 16:19
  • @Jeff not using any thing like nano , gedit etc. – rɑːdʒɑ Dec 13 '13 at 16:25
  • Hus787 I have not typed from getting there if you think so else I welcome your interest in my question. – rɑːdʒɑ Dec 13 '13 at 17:16
  • I agree with Jeff's comment... I too have opinion* that the file stream has to be opened to write to it, whether you use any text editors, or redirection. (*appreciate anybody suggedting links to help with the matter) – precise Dec 27 '13 at 19:10
166

Just open your terminal with CTRL+ALT+Tand type as

 > hello.txt

that's it, your data in that file will be cleared with out opening it even .

Example:

enter image description here

| improve this answer | |
  • 7
    Technically the file will be opened. Just not in an editor. – John Dibling Dec 13 '13 at 16:13
  • Is there a way to undo this command? – Nagendra Rao Nov 9 '15 at 15:09
  • @Rao , If its a large like >10GB , may be. But how much extent not sure. – rɑːdʒɑ Nov 9 '15 at 15:11
  • 1
    @souravc John is correct, the file will be open. Shell opens a file for redirection > with flags O_WRITE|O_TRUNC. In fact, this is stated in the bash manual explicitly under Redirecting Output section: "If the file does not exist it is created; if it does exist it is truncated to zero size." – Sergiy Kolodyazhnyy Dec 19 '19 at 8:20
40

The easiest way is to truncate a file is to redirect the output of the shell no-op command (:) to the file you want to erase.

: > hello.txt
| improve this answer | |
  • 2
    Its probably not the easiest (relative to just >) but the fastest for sure..i wonder why it has not been mentioned in any of the answers of this highly viewed question..here, take +1.. – heemayl Nov 15 '15 at 1:49
  • This works with zsh too (accepted answer doesn't work) – Taylan Jun 19 at 12:09
17

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.

| improve this answer | |
  • Thank you for the answer. Please add an example so that it can look more nicely.+1 – rɑːdʒɑ Dec 13 '13 at 17:17
13

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:

enter image description here

| improve this answer | |
  • hey thank you for answering. so little but work to be done right after that also & but still interesting .+1 – rɑːdʒɑ Dec 13 '13 at 10:24
  • > stands for redirection. cat > file will write stdout to file, overwriting any existing file. – souravc Dec 13 '13 at 17:08
5

If a file was created with the name hello.txt and was provided with some texts then the below command in terminalctrl+alt+t will remove all the text in the hello.txt file,

echo "" > hello.txt

enter image description here

| improve this answer | |
  • Thank you for answering , +1. expand it with some example please so it can be look more nice. – rɑːdʒɑ Dec 13 '13 at 10:23
5

Not the shortest answer but...

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:

  • "-s" set the size
  • "0" size will be zero

Clear everything except first 10,000 bytes

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:

  • Run the truncate command for a reasonable larger normal size of 10K
  • Open the file with your text editor and press End
  • Highlight and PgUp to delete the remaining bytes that don't belong (usually recognizable by ASCII garbage characters).
| improve this answer | |
  • truncate is useful, case: sudo truncate -s 0 /var/log/int/*/syslog.* – Vladimir Dec 19 '19 at 4:16
4

Another approach - cp the /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:$ 

Why does this work and how does this work ? The testFile.txt will be opened with O_WRONLY|O_TRUNC flags, which means if the file exists - it will be truncated, which means contents discarded and size set to zero. This is the same flag with which > operator in shell opens the file on the right of that operator.

Next, cp will attempt to read from /dev/null and after reading 0 bytes will simply close both files, thus leaving testFile.txt truncated and contents effectively deleted.

Knowing that, we could in theory use anything that allows us to open a file with O_TRUNC. For instance this:

dd of=testFile.txt count=0

Small difference here is that dd won't perform any read() at all. Big plus of this dd version is that it is POSIXly portable. The dd specifications state:

If the seek= expr conversion is not also specified, the output file shall be truncated before the copy begins if an explicit of= file operand is specified, unless conv= notrunc is specified.

By contrast cp /dev/null testFile.txt isn't necessarily portable, since POSIX specifications for cp cover what happens only if source_file is non-regular and when -r/-R flags are specified (big thanks to Stephen Kitt for pointing this out), but not what happens when -r or -R are omitted, which is the case here. However it appears at least GNU cp defaults to using rule 3 in the same spec, which is truncating the existing file without changing its type.

| improve this answer | |
1
vi filename -c ':1,$d' -c ':wq'

worked the best for me because of the particular permission it had

| improve this answer | |
  • You can improve this answer by elaborating on the problem you had. Also you could explain what the program vi is and what the various parameters and arguments do. – WinEunuuchs2Unix Mar 20 '18 at 23:59
0

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!

| improve this answer | |
  • 4
    Not a good 'cheat' in my opinion, it can change file permissions... – Parto Aug 11 '15 at 10:50
  • 2
    This might be better of deleted. It can lead to problems: permisions can change. If done on a log file it can lead to unexpected behaviour from the service that expects the log to be there and to be writable. – Rinzwind Nov 15 '15 at 5:49
  • While this answer is not the best way as a point of interest: To correct the issues with owner/permission first check the ownership and permissions then append this(adjust as required): && sudo chown user:group hello.txt && sudo chmod 644 hello.txt – Chris Jan 15 '17 at 5:20
  • inode number will be deleted. a new inode number will be created. bad idea. – Dipankar Nalui Sep 25 '19 at 11:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.