【问题标题】:return lines with matching pattern from a file in perl从 perl 中的文件返回具有匹配模式的行
【发布时间】:2013-05-07 18:10:37
【问题描述】:

我需要编写一个 perl 脚本来提取匹配不同模式的行,然后对其进行操作。我已经完成了以下匹配并提取了所有包含匹配模式的行:

my $filetoread = <$curr_dir/p*.out>;
my $filetoreadStrings=`strings $filetoread | egrep \"(Preparing extraction | 100.00%)\"`;
my @ftr = split('\n', $filetoreadStrings);
chomp (@ftr);

my $FirstPattern = (grep /Preparing extraction/, @ftr)[0];
my $SecondPattern = (grep /100.00% done/, @ftr)[0];
print "$FirstPattern \n";
print "$SecondPattern \n";

我只得到第二个模式的行,即使第一个模式(准备提取)存在于日志中。我认为问题在于或'|'。我需要知道如何获得与模式匹配的所有行。 [$curr_dir 是我运行脚本的目录,P*.out 是日志文件]

【问题讨论】:

    标签: regex perl


    【解决方案1】:
    `... egrep \"(Preparing extraction | 100.00%)\" ...`
    

    应该是

    `... egrep \"(Preparing extraction| 100.00%)\" ...`
    

    或者只是

    `... egrep "(Preparing extraction| 100.00%)" ...`
    

    my $filetoread = <$curr_dir/p*.out>;
    

    应该是

    my ($filetoread) = <$curr_dir/p*.out>;
    

    不要在标量上下文中调用&lt;glob_pattern&gt;,除非你调用它直到它返回undef。


    my @ftr = split '\n', `...`;
    chomp(@ftr);
    

    应该是

    my @ftr = split /\n/, `...`;
    

    chomp( my @ftr = `...` );
    

    【讨论】:

    • 嘿谢谢!!有效。所以“或”之间有一个额外的空格?你能解释一下“my ($filetoread)”的原因吗?
    • 我确实解释了,但我会补充一点:因为如果你不这样做,它会导致你程序中的任何后续 glob 无法正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 2016-11-02
    • 2021-09-27
    相关资源
    最近更新 更多