Perl正则表达式跨多行

时间:2019-11-15 15:50:57

标签: regex perl

我有2个输入文件。

$> cat file1.txt
! This is a comment in file1.txt
// Another comment and below line is an empty line

SIR 8 
    TDI(03)
    TDO(01)
    MASK(03);

$> cat file2.txt
! This is a comment in file2.txt
// Another comment and below line is an empty line

sir 8 tdi(03) tdo(01) mask(03);

现在,我正在尝试编写一个脚本,以收集所有这些“先生”行。这就是我所拥有的:

while(<>) {
    # Skip over all lines that start with ! or are empty or start with //
    next unless !/^!/ and !/^\s*$/ and !/^\s*\/\//;

    # I'm using the modifier /i to be case insensitive
    if(/sir\s+\d+\s+tdi\(\d+\)\s+tdo\(\d+\)\s+mask\(\d+\)\s*;/i) {
        print $_;
    }
}

现在匹配单行上的file2.txt,但不匹配多行上的file1.txt。我在Google上搜索了很多,并尝试了建议的修饰符/ m / s和/ g,但是没有运气。请您帮我找到正确的语法吗?

1 个答案:

答案 0 :(得分:3)

您正在一次阅读一行并与之匹配,因此您可能无法匹配跨越多行的内容。

通过取消定义$/一次读取整个文件是最简单的。

local $/;

while (<>) {
    while (/^sir\s+\d+\s+tdi\(\d+\)\s+tdo\(\d+\)\s+mask\(\d+\)\s*;/mig) {
        print "$&\n";
    }
}

/m使^与行首匹配。

if (//)代替while (//g)可以使我们得到所有匹配项。


单线,

perl -0777ne'CORE::say $& while /^SIR[^;]*;/mig'

Specifying file to process to Perl one-liner