Tweet

Can I make changes to a file without using a temporary file?

I have some code that makes changes to the contents of a file and writes the changes to a temporary file. I then have to rename the temporary file back to the original file.

Is there a way to do this without ever needing to create a temporary file?

The -i flag

When you run Perl with the -i flag it allows you to edit files in place, (and optionally to create a backup file).

For example:

    perl -pi -e 's/abc/XYZ/g' file.txt

will overwrite the original file.txt file with the edited file, and substitute all occurences of the string abc with the string XYZ.

Making a backup file

If you provide an argument for the -i flag, this will allow you to edit files in place, and make a backup file at the same time.

For example:

    perl -pi'.orig' -e 's/abc/XYZ/g' file.txt

will make changes to file.txt and save the original file in file.txt.orig

See also

See perldoc perlrun for more info.

Revision: 1.2 [Top]