fschmitt's answer is the best when using sed; however, in a more general sense this anti-pattern:
cat infile | filter > infile
is likely to cause you a good number of problems. For instance if I have a file called
infile that looks like this:
and run this command:
cat infile | tr "[:upper:]" "[:lower:]"
But if I run
cat infile | tr "[:upper:]" "[:lower:]" > infile I will get an empty file. Why?
Well, when you use the output redirection operator
> you are saying "Put my standard output into this file, and if that file exists overwrite it." Now you may think that this should work since your filter will return all the lines of the original file. However, what often ends up happening is that the shell will clobber your file before any lines are read. Then, your filter command will go to read lines from an empty file, find none, and thus return none. In some places you might get "lucky" enough to have some lines read before the file gets clobber, but it is best to just avoid this pattern altogether.
To get around this particular issue you have a few options. One is to simply do something like:
cat infile | filter > tmpfile; mv tmpfile infile
If you need to be sure that your temp file won't clobber some other file or have other nasty things happen to it, you should look into
man mktemp and
info coreutils mktemp)
Another option is to use
sponge from moreutils.
Also, many of these examples are examples of useless uses of cat.