Instead of updating the file so that it reads parts of the file and modifies them, you ought to make a copy of the file with the changes you want. You can just read the file from stdin (many shells...