Page 1 of 1

Redirection just stopped working eh?

Posted: Thu Aug 16, 2007 6:08 am
by Ollie Saunders
This

Code: Select all

for i in *; do sed "s/Test/Validate/g" $i; done
prints all the files replacing Test with Validate, I get a lot of output, as I would expect

This

Code: Select all

for i in *; do sed "s/Test/Validate/g" $i > $i; done
truncates all the files to nothing, what's going on?

Posted: Thu Aug 16, 2007 6:19 am
by timvw
It's explained in http://docs.babitch.com/O'Reilly/unix/s ... h02_03.htm

2.3.2.1 Saving output

Unless you are redirecting the output of sed to another program, you will want to capture the output in a file. This is done by specifying one of the shell's I/O redirection symbols followed by the name of a file:

$ sed -f sedscr list > newlist

Do not redirect the output to the file you are editing or you will clobber it. (The ">" redirection operator truncates the file before the shell does anything else.) If you want the output file to replace the input file, you can do that as a separate step, using the mv command. But first make very sure your editing script has worked properly!

In Chapter 4, Writing sed Scripts, we will look at a shell script named runsed that automates the process of creating a temporary file and using mv to overwrite the original file.

Posted: Thu Aug 16, 2007 6:20 am
by Ollie Saunders
Well, that just sucks

Posted: Thu Aug 16, 2007 6:38 am
by Jenk
but it makes sense.. you are overwriting the file you want to edit before you have edited it when using the > operator.

Code: Select all

for i in *; do sed "s/Test/Validate/g" $i > temp && mv temp $i; done