in reply to Replacing a string in a file

If I want to be sure that my files don't get corrupted by a second process writing to it, I usually do it the way I described in Re: What is the best way to lock a counter file?.

Maybe this will help you.