Friday, July 30, 2010

Unix File Redirection: How to Overwrite an Existing File

I have set my tc shell settings so that when ever I try to redirect command output to an existing file, it gives me an warning. The reason for why I am using this option is that while redirecting to a file, you loose all the contents of the file. If you make a mistake while typing the file name, this can lead to very dangerous outcome. Because that file may contain data whose backup you don't have.

But, this option has some drawbacks also. That is when you want to rewrite a file by redirect to it. The problem is every time you try to do this, you are given an warning. What you have to do is to remove the file first, then redirect to that file. Two steps become involved which eats many time. But, today I have found that there is a way to perform these steps by just one. It is adding the "!" sign at the end of ">" sign. Here is the example.

% echo hello world! > test.txt
% cat test.txt
hello world!
% echo again hello world > test.txt
test.txt: File exists.
% echo again hello world >! test.txt
% cat test.txt
again hello world!


In this example, I first redirect the output of the command "echo" to file "test.txt". As "test.txt" file does not exist, shell creates a new file and writes the output to this file. Next, I redirect the output of another "echo" command to this same file and this time, shell gives me an warning. Now, if I do this by adding the "!" sign after ">", shell overwrites the existing file and writes the new output result to that file. This trick will surely save a lot of my time.

No comments:

Post a Comment