Redirect overwrites itself

I bet many people faced this problem before:

The command below will result in a blank file:

$ cat myfile | grep pattern > myfile

Is there any easy way to do it?

Yes. Don't do it :smiley:

Write to another file, and copy the new file over the old one if you have to.

I've always done that, but it seems like a waste of time.
There has to be a general solution for this problem. :(:(:(:(:frowning:

sed -ix -n "/pattern/p" file1
sed -ie '/pattern/!d' myfile

Handle with care! :smiley:

Grep was just an example. Let's say I'm editing the file with tr,cut,awk,etc.
We can't rely on sed for everything.

Ps: thanks a lot for your response Scottn, but I believe there has to be a better way.

The sed ways shown above is the GNU sed way - not the (for my two cent's worth) standard way.

The other tools that you mention, GNU or otherwise, most likely don't have that "flexibility".

Hi.

See post #4 at Sed does not make changes in the file but to the standard output

See moreutils for code of the original utilities ... cheers, drl

Not sure if this qualifies as "easy", but if you're the adventurous type:

(rm myfile; grep -v pattern > myfile) < myfile

I elaborate on how this works and the risks involved at the end of the post at How to use sed to replace the a string in the same file using sed? Post: 302407978

Regards,
Alister