如何在perl中匹配和替换多行

时间:2015-04-10 15:37:42

标签: perl

我在使用perl,但我不认为这会产生影响 我想用另一行替换文本文件(称为copy.conf)中的一行。

该行是

#file1
file = User/me/stuff.txt #This filename can vary

我想用

替换它
#file1
file = Another/Path/tostuff.txt

为了做到这一点,我需要匹配#file1以及以下文件=以及该行上的所有其他内容。所以我尝试了如下的多行匹配

 perl -i -p -e's{#file1\n.*}{#file1\n Another/Path/tostuff.txt}g' /Users/copy.conf

虽然我没有收到错误,但我也没有得到理想的结果。在进一步测试时,     #file1的/ N

似乎很好,但是     *。 事后没有。所以我尝试使用多行标志来查看其是否有效:

perl -i -p -e's{#file1\n.*/m}{#file1\n Another/Path/tostuff.txt}g' /Users/copy.conf

but I get the same result.

2 个答案:

答案 0 :(得分:2)

行。这里的问题是:

  • \n而非/n
  • 您的m需要位于模式的末尾:s{#file1\nfile =.*}{#file1\nfile = Another/Path/tostuff.txt}gm
  • -p在您的代码周围定义了一个逐行循环的while循环。所以你需要local $/;来哄骗所有人。

尝试改为(没有工作,忍受我):

perl -i.bak -p -0777 -e 's{#file1\n.*}{#file1\nfile = Another/Path/tostuff.txt}mgs;' test.txt

没有内联,这有效;

#!/usr/bin/perl

use strict;
use warnings;

local $/;
while ( <DATA> ) {
    s{#file1\nfile =.*}{#file1\nfile = Another/Path/tostuff.txt}gm;
    print;
 }
__DATA__
#file1
file = User/me/stuff.txt #This filename can vary

答案 1 :(得分:1)

我根本不是单行的粉丝,但这对你有用。如果当前行以#file1开头,则会读取下一行,将file =后的所有内容替换为新路径,并将其附加到$_

perl -i -pe'$_ .= <> =~ s|file\s*=\s*\K.+|Another/Path/tostuff.txt|r if /^#file1/' copy.conf