Perl - Replacing a file

December 2016




Issue


When I'm in my favorite shell, I carry replacements via:
perl -pi -e 's/lib\/nagios/lib64\/nagios/g' /etc/nagios/nrpe.cfg

I would like to reuse this replacement file, but use a script in Perl, not to run online
And I find it stupid to use a
system ( "perl -pi -e 's/lib\/nagios/lib64\/nagios/g' /etc/nagios/nrpe.cfg ")

how do I do, ideas?

Solution


You can use this :
$file = "/etc/nagios/nrpe.cfg";

open (FILE, "<$file");
@lines = <FILE>;
close FILE;
                
open (STDOUT, ">$file");    
for ( @lines ) {
    s+lib/nagios+lib64/nagios+g;
    print;
}

close STDOUT;

Note


Thanks to Dubcek for this tip.

Related :

This document entitled « Perl - Replacing a file » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.