【问题标题】:perl search and replace with new linesperl 搜索并用新行替换
【发布时间】:2015-05-30 12:04:24
【问题描述】:

我需要能够运行一个 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/;

【问题讨论】:

标签: perl


【解决方案1】:

我会使用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");

【讨论】:

  • 我正在处理的服务器的管理员不允许我添加任何模块,并且该服务器缺少 IniFiles.....
【解决方案2】:

这就是我所做的:

    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;

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

【讨论】:

    猜你喜欢
    • 2015-08-24
    • 2010-11-05
    • 2021-01-31
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2015-02-20
    • 2017-01-05
    • 2013-05-20
    相关资源
    最近更新 更多