Re: shell script replacing original file



On 2008-03-28, Maxwell Lol wrote:
"Ming Ching TIew" <nospam@xxxxxxxxxx> writes:

I want to know if it is 100 % safe to do this :-

$ cat myfile | sed -e '...........' > myfile

(p.s. No need for cat.)

In this case, cat is needed so that myfile is opened before the
redirection truncates it. Even so, I wouldn't trust it.

Well, if you want to be 100% safe, perhaps something like this is better

sed -e '...........' <myfile > myfile.new
mv myfile myfile.old && mv myfile.new myfile && /bin/rm myfile.old

If it's a large file, and the disk fills up, it won't delete the
original file. (untested)



--
Chris F.A. Johnson, author <http://cfaj.freeshell.org/shell/>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence
.



Relevant Pages

  • Re: let built-in doesnt work as expected
    ... I have a file (myfile) containing the following lines: ... There are two problems with your script. ... The first problem can be solved by using redirection instead of ... cat; the second by reading the components of each line: ...
    (comp.unix.shell)
  • Re: shell script replacing original file
    ... of the original file:- ... Looks fine but using perl it is much simpler. ... % cat test.txt ...
    (comp.unix.shell)
  • Re: matching column variables from two awks!
    ... $ cat df_out ... cat df_out | awk -f tst.awk myFile - ... awk '' myFile df_out ... and copy/paste the result into a posting so we can see what you're working with. ...
    (comp.lang.awk)
  • Re: stdout , stderr
    ... mxa@yahoo.com (michael) wrote: ... > cat: Cannot use myfile as both input and output. ... tell you the filename that's the same because you *told* it the filename ...
    (comp.unix.shell)
  • Re: Combine avi files
    ... > Joost van der Waa wrote: ... Yes of course, 'cat' will work ... >>I'm just wondering wether you will still be able to play the concatenated ... > You'd normally use split to cut the original file into smaller pieces. ...
    (alt.os.linux.suse)