Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

The following command works fine:

sed s/input/raw_input/ p.py >p2.py && mv p2.py p.py

However, the following command turns p.py into an empty file:

sed s/input/raw_input/ p.py >p.py

The following also turns p.py into an empty file:

sed s/input/raw_input/ p.py | cat > p.py

Why don't the last two commands behave as expected? In particular why is p.py empty?

share|improve this question
add comment

1 Answer 1

up vote 10 down vote accepted

This is because the redirection operator > is called before any command and thus the following happens in this order:

  1. p.py is opened for writing, truncating whatever was there before
  2. sed is called to perform commands on p.py which is now empty
  3. The output (which is nothing) is written to p.py (so it still contains nothing)

You have two options depending on how portable you want your code to be:

not portable

Use GNU sed -i option to do an in-place edit

portable

redirect the output to a temp file then move the temp file over the original after sed is complete

share|improve this answer
    
Is the order of steps 1 and 2 is well defined; in other words, can you actually count on it emptying the file before sed opens it? (Of course if you simply avoid writing such ugly commands it doesn't matter.) –  Keith Thompson Feb 13 '12 at 5:40
3  
@KeithThompson Yes, this is well defined by the shell. Not sure what you mean by ugly commands though, redirecting to a file is a common, and non-ugly, thing to do. –  SiegeX Feb 13 '12 at 5:45
    
A third option, if you'd rather not have to deal with making temp files, is to use ed instead. –  jw013 Feb 13 '12 at 6:10
    
I'd call redirecting to a file that you're reading ugly (no offense to the OP intended). –  Keith Thompson Feb 13 '12 at 6:15
1  
@KeithThompson ahh, yes. In that case I would call it broken more than anything ;) –  SiegeX Feb 13 '12 at 7:01
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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