One way of scripting the editing of a file is to generate a stream of commands and pipe them into 'ed' or 'ex'. 'ed' is so basic that it tends to be forgotten, but it is clean and concise, and performs the edit in place with no need for moving a newly created modified version of the old file into place. The change happens on the write, so unless the file being edited is longer than the system write size there is little chance of it changing between reads of the file by another process. If a process has the file open before the edit, however, it will see different data before and after if data moves across the system buffer size. If the edit to new the move approach is used, the process will continue to see the old file unless it closes and re-opens it.
The command stream can be created with a simple echo:
q" | ed filename
to delete line 1 of the file; or it could be a 'here' document:
ed <<EoC filename
or in a complex case, such as a passwd file edit, it could be generated by an 'awk' script.