Redirection just stopped working eh?

Whether you are using Linux on the desktop or as a server, it's still good that you're using Linux. Linux related questions go here.

Moderator: General Moderators

Post Reply
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Redirection just stopped working eh?

Post 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?
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Well, that just sucks
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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
Post Reply