The best way to do this is to remember how files work in unix -- the file exists as long as there is a link to the file (directory or process opening the file).
So, open the file, delete that directory entry, then run your process that writes to a new directory entry with the same name but linked to a different inode.
Lastly, the nice thing about this is that it works for any sort of pipeline operation, not just things that can do the temporary file buffer hack.
{ rm file ; sed -e s/this/that/g > file ; } < file
A word of warning -- this may cause disaster if you must have your rewrite be an atomic operation. unix doesn't offer clean ways of locking files, especially not at shell level. This was an issue in the dark ages if you were doing something like editing a password file on a busy system that was running something like NIS. Any time more than one process is reading / writing to a file, be very careful if your system is busy or important.
The only operations that are 100% certain to be atomic are directory entry manipulations -- rm / ln / mv (on the same filesystem).
So now things get longer and uglier..
The math part of this requires a posix shell or similarly extended bourne shell
c=0
while
f=$SECONDS
test -f file.$c.tmp
do
c=$(($c+1))
done
grep stuff < file > file.$c.tmp && mv file.$c.tmp file