Given the new information you have provided, the most reasonable approach is following tilly's advice. There is no good reason to attempt in-place editing when output-and-move is sooo much easier and less bug-prone.
Comment on Re^3: Replace current line in while loop