Hi
Quote:
Originally Posted by bakunin
The reason is: sed will read the first line of the input file (which is "file"), apply any rules that might be applicable and then write the result (the changed or not changed line) to <stdout>. This <stdout> is at this moment pointing to "file" and this is why after the first line the file will contain nothing more than exactly that first line - so sed encounters the EOF and thinks it is finished.
I would have explained this behaviour somewhat differently: when the shell begins to process a command line, it will literally remove the characters that involve re-direction. In dealing with re-direction, the shell will "zero" a file that is being re-directed to. If there was data on the file, it will have been erased before the command is executed. The result is that the command -- in this case
sed -- will never see any input, because it already has been destroyed. The first read will encounter EOF.
Most of us have fallen into this operational trap. For example, we often want to sort a file onto itself -- just re-ordering data, neither gaining or losing data. So
sort has an option to write the output to the input file, but one must use "-o file", and not "> file". The GNU
sed allows a similar construction with "in-place" editing, but what actually happens is that sed writes to a temporary file and then renames it at the end. You can see this if you display the inode number (
ls -li file) before and after the operation. You'll see that they are different.
The flow-chart of shell operations is displayed in some books, for example, O'Reilly's
Learning the bash shell, 2nd, page 177 ff ... cheers, drl