1

I have a command that strives to just read a file and then comment out every single line in it indiscriminately, then overwrite the existing file.

cat file | sed 's/^/#/g' > file

But to my surprise this doesn't actually work and actually just produces a blank file. From my understanding of pipes this shouldn't happen given that stdout goes to sed, is processed by sed and then sent to the file. So I'd like to know why this is happening

In place of my expected behavior I implemented a workaround.

cat file | sed 's/^/#/g' > /tmp/file; mv /tmp/file file

Why does my does my original solution not work though?

marked as duplicate by Anthon, Gilles shell Feb 18 '15 at 23:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5

Your original solution does not work because as soon as you redirect, the shell creates an empty file by that name. You can use the -i option of sed to fix this problem. For example,

sed -i 's/^/#/g' file

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