Redirection not overwriting file but just producing a blank one

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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply