|Home » Faqs » Perl thinking » Edit in place|
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?
When you run Perl with the
-i flag it allows you to edit files in place,
(and optionally to create a backup file).
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
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.
perl -pi'.orig' -e 's/abc/XYZ/g' file.txt
will make changes to
file.txt and save the original file in
perldoc perlrun for more info.