如何在perl中修改.ini文件

时间:2013-01-11 09:18:20

标签: perl

我正在尝试编写一个脚本,它将在InI文件中修改4行:

以下是我的Ini文件的内容:

gEnableImps=1
gEnableBmps=1
gEnableSuspend=3
gDot11Mode=0
gEnableHandoff=0
gRoamingTime=0 


Intf0MacAddress=000AF6798980
Intf1MacAddress=000AF5788981
Intf2MacAddress=000AF2898982
Intf3MacAddress=000AF5893983


InfraUapsdVoSrvIntv=0 
InfraUapsdViSrvIntv=0
InfraUapsdBeSrvIntv=0
InfraUapsdBkSrvIntv=0 


DelayedTriggerFrmInt=18000


gEnableFWRssiMonitoring=0  

我必须每天修改四行以下:

Intf0MacAddress=000AF6798980
Intf1MacAddress=000AF5788981
Intf2MacAddress=000AF2898982
Intf3MacAddress=000AF5893983

在上面的行中,我需要更改6798980,5788981,2898982,5893983部分我的意思是在每个数字中任何一个连续的数字应该得到改变,并且更改数字不应该得到另一个数字的副本,即在每个数字中唯一的数字应该改变。

Exp:

6798980  after change -> 6791280
5788981  after change -> 5783481   
2898982  after change -> 2897682

我已编写代码,但我无法更改数字..任何机构都可以给我一些帮助

我的剧本:

#!/usr/bin/perl -w
use strict;
open(FH,"+<","WCN1314_qcom_cfg.ini")
                       or die "File not found";

my @lines=<FH>;
foreach my $line (@lines)
{
  if(($line =~ /Intf0MacAddress/ ||$line =~ /Intf1MacAddress/||$line =~ /Intf2MacAddress/||$line =~ /Intf3MacAddress/) )
{
  print "$line\n";
}  
else
{
  print "Not found\n";
}
}  

3 个答案:

答案 0 :(得分:4)

无需通过自行解析和编写.ini文件来重新发明轮子。我建议使用CPAN中的Config::IniFiles或其他类似模块。这段代码只需3行即可完成所需。

my $cfg = Config::IniFiles->new( -file => $file, -fallback => 'GENERAL' );
$cfg->setval('GENERAL', 'Intf0MacAddress', '999999999999');
$cfg->RewriteConfig;

答案 1 :(得分:2)

我不明白你想用数字做什么。你能试着详细解释一下吗?你确定你的例子是正确的吗?你能解释为什么有些数字会改变而有些数字却没有改变吗?

无论如何,您可以使用以下内容:

#!/usr/bin/perl
use warnings;
use strict;

my $file = 'WCN1314_qcom_cfg';
open my $OLD, '<', "$file.ini" or die $!;
open my $NEW, '>', "$file.new" or die $!;
my $digit = 1;
while (my $line = <$OLD>) {
    if (my ($num, $addr) = $line =~ /^Intf([0-3])MacAddress=000AF([0-9]+)/) {
        my @digits = split //, $addr;

        # Do what you need with the digits

        $line = "Intf${num}MacAddress=000AF" . (join q(), @digits) . "\n";
    }
    print {$NEW} $line;
}
close $NEW;
close $OLD;

if (-f "$file.bak") { unlink "$file.bak" or die "Cannot remove backup: $!"; }
rename "$file.ini", "$file.bak"          or die "Cannot backup.";
rename "$file.new", "$file.ini"          or die "Cannot create ini.";

答案 2 :(得分:-1)

#!/usr/bin/perl -w
use strict;
open(FH,"+<","WCN1314_qcom_cfg.ini")
                       or die "File not found";
use 5.010;
my $file=join "", <FH>;

for (my $index = 0; $index < 4; $index++) {
    if ($file =~ m/(Intf($index)MacAddress=000AF)(\d{7})/) {
        my $number = $3;
        #Do what you need with number.
        $file =~ s/$&/Intf($index)MacAddress=000AF($number)/;
    }
}

open(FH,">","WCN1314_qcom_cfg.ini");
print FH $file;
close FH;