Reputation: 1
I am running the following Perl script via ActivePerl to extract the time and ID numerical values from a text. For some reason, the while loop ends after the first line of the text is checked.
Here is the Perl code I use:
#!/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
: (No accountId
entry on third line)
{"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
: (Nothing else)
timestamp 1508845227478 account ID1275676
Upvotes: 0
Views: 101
Reputation: 3601
Put the regex in an if statement and make the while loop read every line.
#!/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;
Upvotes: 0
Reputation: 386696
You only ever read one line!
#!/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};
}
Usage:
script nr_raw.txt >results.txt
Upvotes: 3