Linux sed Behavior – Why sed Acts Differently Depending on Output File

linuxpipesed

If I run:

cat messages.txt | sed -e 's/a/a/g' > messages.txt

on one large file (2500+ lines) I find that the resulting file will only have about 900 lines after the command in cygwin and will have no lines in gentoo. However if I run

cat messages.txt | sed -e 's/a/a/g' > other_messages.txt

it retains all the lines as it should.

My question is why and is there any way to do it other than

cat messages.txt | sed -e 's/a/a/g' > other_messages.txt
rm messages.txt
mv other_messages.txt messages.txt

Best Answer

Why don't you just write

sed -i -e 's/a/a/g' messages.txt

the -i means "in place"

Related Question