【问题标题】:Replace a line in PERL with other line将 PERL 中的一行替换为其他行
【发布时间】:2014-08-27 17:10:30
【问题描述】:

我正在迭代一个文件,然后我必须搜索一个字符串,我必须从该字符串中将一个子字符串替换为另一个字符串。谁能帮我解决这个问题。 我试过这样。

while(<FH>)
{
if($_ =~ /AndroidAPIEventLogging=false/i)
{

if($& =~ s/false/True/)
{
print("Changed successfully\n");

}

}

} 

现在显示它只能执行读取操作。我尝试以每种可能的模式打开文件。

【问题讨论】:

    标签: string perl replace


    【解决方案1】:

    匹配和替换是某种 perl 反模式,因为您匹配(通常是相同的字符串)两次,所以回到您的问题

    while (<FH>) {
      # everything before '\K' is not replaced (positive look behind)
      if (s/AndroidAPIEventLogging=\Kfalse/True/i) { # $_ =~ 
    
        print("Changed successfully\n");
      }
    }
    

    【讨论】:

      【解决方案2】:

      您可以通过 Perl 单行使用 -i option 来做到这一点

      perl -i -pe 's/AndroidAPIEventLogging=false/AndroidAPIEventLogging=true/i' file1 file2...
      

      作为替代方法,请查看Tie::File。它似乎是为快速就地文件编辑而设计的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-24
        • 1970-01-01
        • 1970-01-01
        • 2012-10-16
        • 2022-11-13
        • 1970-01-01
        • 2021-10-24
        • 1970-01-01
        相关资源
        最近更新 更多