2011-01-21 8 views
1

私はパイプで区切られたファイルを本当に混乱させました。これはデータベースにロードする必要があります。このファイルには35個のフィールドがあり、したがって34個のパイプがあります。フィールドの1つは、レコードによっては複数の改行が含まれているHTMLコードで構成されています。残念ながら、改行がどこに落ちるかについての後藤はありません。各行が特定の文字の特定のインスタンス数を持つまで、改行文字を削除する方法はありますか?

解決策は、各行のパイプ数を数え、その数が34に達するまでその行から新しい行文字を削除することです。私はPerlに非常に精通していませんが、私がやりたいことを達成することに近いと思います。助言がありますか?

#!/usr/local/bin/perl 

use strict; 

open (FILE, 'test.txt'); 

while (<FILE>) { 
    chomp; 
    my $line = $_; 
    #remove null characters that are included in file 
    $line =~ tr/\x00//; 
    #count number of pipes 
    my $count = ($line =~ tr/|//); 
    #each line should have 34 pipes 
    while ($count < 34) { 
     #remove new lines until line has 34 pipes 
     $line =~ tr/\r\n//; 
     $count = ($line =~ tr/|//); 
     print "$line\n"; 
    } 
} 
+0

参照:http://stackoverflow.com/questions/6075327/how-do-i-handle-store-multiple-lines-into-a-single-field-read-from-a-file -in-perl – mob

答えて

1

これは私が推測するはずです。

#!/usr/bin/perl 

use strict; 

open (FILE, 'test.txt'); 

my $num_pipes = 0, my $line_num = 0; 
my $tmp = ""; 
while (<FILE>) 
{ 
    $line_num++; 
    chomp; 
    my $line = $_; 
    $line =~ tr/\x00//; #remove null characters that are included in file 
    $num_pipes += ($line =~ tr/|//); #count number of pipes 
    if ($num_pipes == 34 && length($tmp)) 
    { 
      $tmp .= $line; 
      print "$tmp\n"; 
      # Reset values. 
      $tmp = ""; 
      $num_pipes = 0; 
    } 
    elsif ($num_pipes == 34 && length($tmp) == 0) 
    { 
      print "$line\n"; 
      $num_pipes = 0; 
    } 
    elsif ($num_pipes < 34) 
    { 
      $tmp .= $line; 
    } 
    elsif ($num_pipes > 34) 
    { 
      print STDERR "Error before line $line_num. Too many pipes ($num_pipes)\n"; 
      $num_pipes = 0; 
      $tmp = ""; 
    } 
} 
+0

完璧に働いた、ありがとう! – user584982

1

$/とひねり、input record separator

while (!eof(FILE)) { 

    # assemble a row of data: 35 pipe separated fields, possibly over many lines 
    my @fields =(); 
    { 
     # read 34 fields from FILE: 
     local $/ = '|'; 
     for (1..34) { 
      push @fields, scalar <FILE>; 
     } 
    } # $/ is set back to original value ("\n") at the end of this block 

    push @fields, scalar <FILE>; # read last field, which ends with newline 
    my $line = join '|', @fields; 
    ... now you can process $line, and you already have the @fields ...... 
} 
+0

私は決して考えなかったような、うわー、面白い方法。 – user584982

関連する問題