in reply to Re: Re: In-place editing in a script
in thread In-place editing in a script

It's very simple to do search and replace with s/// on simple config files, without using any modules. And you don't need a temporary file either, just load the entire config file into memory, search and replace keys, and write it back to the config file. Perl is great at doing this kind of stuff.

use strict; use Data::Dumper; my @config; { local $/ = '['; @config = <DATA>; } SetConfigKey(\@config, 'bdstest', 'Location', 'Somewhere'); SetConfigKey(\@config, 'bdstest', 'OS', 'WindowsXP'); SetConfigKey(\@config, 'custard', 'MainFunction', 'Perl Perl Perl'); SetConfigKey(\@config, 'custard', 'SCSI', 'YES'); print @config; sub SetConfigKey { my ($config, $section, $key, $value) = @_; foreach (@{$config}) { # loop through config sections next if ! /^$section\]/; # skip if unwanted s/\Q$key\E\s*=.*/$key=$value/; # replace the value } } __DATA__ [bdstest] MainFunction= SystemType=U5 Env= Location= Serial=FW0094810719 Hostid=80c0dc14 OS=Solaris Version=8 Disk=1x8 Memory=128 CPU=1x360 qfe= SCSI= GraphACC= SupportContract= #END [custard] MainFunction= SystemType=U5 Env= Location= Serial=FW00250126 Hostid=80c0aee2 OS=Solaris Version=8 Disk=1x8 Memory=256 CPU=1x360 qfe= SCSI= GraphACC= SupportContract= #END
And the output is -
[bdstest] MainFunction= SystemType=U5 Env= Location=Somewhere Serial=FW0094810719 Hostid=80c0dc14 OS=WindowsXP Version=8 Disk=1x8 Memory=128 CPU=1x360 qfe= SCSI= GraphACC= SupportContract= #END [custard] MainFunction=Perl Perl Perl SystemType=U5 Env= Location= Serial=FW00250126 Hostid=80c0aee2 OS=Solaris Version=8 Disk=1x8 Memory=256 CPU=1x360 qfe= SCSI=YES GraphACC= SupportContract= #END