perl搜索并替换为新行

时间:2015-05-27 04:01:05

标签: perl

我需要能够运行一个perl脚本来搜索并替换[RemotePhoneBook0]下的3行

所以这是文件的摘录:

[ RemotePhoneBook0 ]
path = /config/Setting/Setting.cfg
URL =
Name =

[ RemotePhoneBook1 ]
path = /config/Setting/Setting.cfg
URL =
Name =

我无法触摸[RemotePhoneBook1]。当我完成时,上面的相同摘录应该如下:

[ RemotePhoneBook0 ]
path = /somePath/to/someDir
URL = someUrl
Name = someName

[ RemotePhoneBook1 ]
path = /config/Setting/Setting.cfg
URL =
Name =



s/^<<<what can i put here>>>\s*=.*/somePath/;
s/^<<<what can i put here>>>\s*=.*/someUrl/;
s/^<<<what can i put here>>>\s*=.*/someName/;

2 个答案:

答案 0 :(得分:2)

我将Config::IniFiles用于此类任务:

use warnings;
use strict;

use Config::IniFiles;

my $ini = Config::IniFiles->new( -file => "stackoverflow_30472923.ini" );

# print $ini->val("RemotePhoneBook0", "path");

$ini -> setval('RemotePhoneBook0', 'path', '/somePath/to/someDir');
$ini -> setval('RemotePhoneBook0', 'URL' , 'someUrl'             );
$ini -> setval('RemotePhoneBook0', 'Name', 'someName'            );

$ini -> WriteConfig("stackoverflow_30472923.modified.ini");

答案 1 :(得分:0)

对于后人来说,这就是我所做的:

    open my $in,"<","$directory/$files";
    open my $out,">","$directory/temp.txt";

    my @lines = <$in>;
    close $in;
    #print "@lines";
    for($index=0;$index<=$#lines;$index++){
            my $this = $lines[$index];
            if ($this eq "[ RemotePhoneBook0 ]\n"){
                    $lines[$index] = "[ RemotePhoneBook0 ]\n";
                    $lines[$index+1] = "path=\n";
                    $lines[$index+2] = "URL = http:\/\/someUrl\n";
                    $lines[$index+3] = "Name = Users\n";
                    $lines[$index+4] = "\n";
                    $index++;
                    $index++;
                    $index++;
                    $index++;
                    }else{
                            $lines[$index] = $this,"\n";
                    }
    }
    print $out @lines;

这会打印每一行,同时替换我关心的行。