in reply to Re: Capture Contents AND Overwrite without Opening Twice?
in thread Capture Contents AND Overwrite without Opening Twice?

Well you could use the -i flag on the command line to modify a file, well at least in a one-liner.

Otherwise, I would not recommend opening files in read-and-write mode. But if you do want to do it this way, then you need to read the full file first and save the content in an array, make whatever changes you need to the array, and then only write back the array to the file. It works, but that would not be my recommended course of actions.

I would suggest reading the input file (read mode), writing to a copy of it (write mode), and then, if everything went OK, to do the house cleaning, i.e. deleting the old file (or archiving it under another name), and renaming the new one to what you need.

  • Comment on Re^2: Capture Contents AND Overwrite without Opening Twice?

Replies are listed 'Best First'.
Re^3: Capture Contents AND Overwrite without Opening Twice?
by Anonymous Monk on Oct 08, 2014 at 22:52 UTC

    This is an important consideration iff the file will be accessed by other processes during the run of the script, or if it's important that the file doesn't get corrupted by either the script dieing or getting shot down externally while it is modifying the file. (probably what MidLifeXis's comment was aimed at as well)