需要帮助在Perl中解析文本文件

时间:2014-10-02 00:23:52

标签: regex perl

我的文件格式为file1.txt,格式如下所示

1
A:  24
B:  6
C: -33

2
A:  44
B:  5
C:  78

3
A:  32
B: -98
C:  22

我需要我的perl程序来解析这个文本文件并输出为file2.txt:

      1      2      3
 A    24     6     -33      
 B    44     5      78
 C    32    -98     22

提前感谢您的帮助

尝试了一些事情,但这种方式无法正常工作。但根据其他人的反馈,我发布了代码。

# Program to parse output
@split1 = split(/\//,$ENV{'DESIGN_PATH'});

open (FILE1,"<path_to_file1.txt");
open (FILE2,">path_to_file2.txt"); 
my $go = 0;

while ($line = <FILE1>) {
print $line;
# Remove Blank SPaces
chomp $line;
@sp = split(/ /,$line);

$n=0;
for ($i=0; $i<=$#sp; $i++) {
  if ($sp[$i] eq "") {
  } else {
  $arry[$n] = $sp[$i];
  $n++;
  }
}

if ($line =~ /A:/ && $go == 0) {
  $go = 1;
  $group = $arry[$n-1];
  print FILE2 "- -\n";
  print FILE2 "B $arry[$n-1]\n";
}

if ($line =~ /B:/ && $go == 1) {
  $go = 0;
  print FILE2 "B: $arry[$n-1]\n";
} elsif ($line =~ /C:/ && $go == 1) {
  print FILE2 "C: $arry[$n-1]\n";
}


}
close FILE1;

1 个答案:

答案 0 :(得分:2)

将您的数据累积到HoH或其他数据结构中,然后输出:

use strict;
use warnings;

use List::MoreUtils qw(uniq);

my %data;

local $/ = '';    # Paragraph mode
while (<DATA>) {
    chomp;
    my ( $column, $vals ) = split "\n", $_, 2;

    while ( $vals =~ m/(.*):\s*(.*)/g ) {
        $data{$column}{$1} = $2;
    }
}

my @columns = sort keys %data;
my @rows = sort +uniq map { keys %$_ } values %data;

print join( "\t", '', @columns ), "\n";
for my $row (@rows) {
    print join( "\t", $row, map { $data{$_}{$row} // '' } @columns ), "\n";
}

__DATA__
1
A:  24
B:  6
C: -33

2
A:  44
B:  5
C:  78

3
A:  32
B: -98
C:  22

输出:

    1   2   3
A   24  44  32
B   6   5   -98
C   -33 78  22