虽然循环在正则表达式上过早结束

时间:2017-10-27 00:17:11

标签: regex perl

我通过ActivePerl运行以下Perl脚本,从文本中提取时间和ID数值。 出于某种原因,while循环在检查文本的第一行之后结束。

这是我使用的Perl代码:

#!/usr/bin/perl -w
$inputfile = "nr_raw.txt";
$outputfile = "results.txt";  #create this output file (it will be created automatically in the current folder)
open (OUTPUTFILEHANDLE, "> $outputfile") || die "I can't find or open $file: error $!\n";
open (INPUTFILEHANDLE, $inputfile) || die "I can't find or open $file!\n";
$_=<INPUTFILEHANDLE>;
while (/{.*?"timestamp":(\d+).*?"accountId":(\d+).*?}\n/sg)
{
$info="timestamp: $1 accountID: $2";
print "$info \n";
print OUTPUTFILEHANDLE $info ;
}
close OUTPUTFILEHANDLE;

nr_raw.txt :(第三行没有accountId条目)

{"eventType":"alarm","timestamp":1508845227478,...,"accountId":1275676,"Version":"1.3",....}
{"eventType":"alarm","timestamp":1508845166740,...,"accountId":1274721,"Version":"1.1",....}
{"eventType":"alarm","timestamp":1508845187479,....,..................,"Version":"1.1",....}
{"eventType":"alarm","timestamp":1508845166980,...,"accountId":1347376,"Version":"1.2",....}

results.txt :(没什么)

timestamp 1508845227478 account ID1275676

2 个答案:

答案 0 :(得分:3)

你只读过一行!

#!/usr/bin/perl

use strict;
use warnings;
use Cpanel::JSON::XS qw( );

my $parser = Cpanel::JSON::XS->new();

while (<>) {
    my $rec = $parser->decode($_);
    print("timestamp: $rec->{timestamp} accountID: $rec->{accountId}\n")
        if $rec->{accountId};
}

用法:

script nr_raw.txt >results.txt

答案 1 :(得分:0)

将正则表达式放在if语句中,并使while循环读取每一行。

    #!/usr/bin/env perl
    use strict;
    use warnings;
    use autodie; # See http://perldoc.perl.org/autodie.html

    my $inputfile = "nr_raw.txt";
    my $outputfile = "results.txt";  #create this output file (it will be created automatically in the current folder)

    # autodie handles errors automatically.
    open my $out_fh, '>', $outputfile;
    open my $in_fh, '<', $inputfile;

    while( my $line = <$in_fh> ){
        if( $line =~ /{.*?"timestamp":(\d+).*?"accountId":(\d+).*?}\n/sg ){
            my $info = "timestamp: $1 accountID: $2";

            print "$info \n";
            print $out_fh $info ;
        }
    }

# autodie handles errors automatically.
close $out_fh;
close $in_fh;