Sed question


#1

I was fooling around in the terminal and I just wanted to ask why this command here doesn't work:

sed 's/snow/rain/g' forests.txt > forests.txt

What I thought would happen was that all entries containing snow would be changed to rain, and then that resulting file would be overwritten to forests.txt. However what actually happens is that it deletes everything in the forests.txt file, meaning there will no longer be any entries in the file.

Can anyone explain why that happens?


#2

Here is a explanation for why the file is empty:

tl;dr, and substituting grep for sed:

The reason why you can't do that: bash processes the redirections first, then executes the command. So by the time grep looks at file_name, it is already empty