2017-10-27 7 views
0

私はActivePerlで次のPerlスクリプトを実行して、テキストから時刻とID数値を抽出しています。 何らかの理由により、テキストの最初の行がチェックされた後にwhileループが終了します。whileループが途中で正規表現で終了する

#!/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:ここ

は、私が使用するPerlのコードではありません(3行目の何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 
+4

perl 5.0のリリースから23年が経過しています。あなたは 'strict 'と' use warnings'を使用できるようになりました。 – melpomene

+4

あなたのコードはファイルから1行だけを読み込みます。 – melpomene

+0

$ _ = ; #ちょうどファイルから最初の行を読む – asthman

答えて

3

ます1つの行だけを読んでください!

#!/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 
+0

ありがとうございました。私はCpanel :: JSON :: XSモジュールをインストールし、それを使用します! –

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; 
+1

私は魅力として働いています、ありがとう。今私はそれがまさに私がやろうとしていたことだと分かります。私は、同じスクリプトが他のテキストファイルで動作していたので混乱しました(たぶんLIN/LFが1つしかないためです)。ありがとうございました! –

関連する問題