从文件中提取Perl模式

时间:2013-03-18 07:57:42

标签: perl

我有一个文本文件,如:

Name : first  
File name : first_1  
Year : 12  
etc  
etc  
etc  
T1 : this is t1  
T2 : this is t2  
T3 : this is t3  
Conclusion : Success  
Name : first  
File name : first_2   
Year : 13  
etc  
etc  
etc  
T1 : this is t1  
T2 : this is t2  
T3 : this is t3  
Conclusion : Success 
Name : second  
File name : second_1  
Year : 12  
etc  
etc  
etc  
T1 : this is t1  
T2 : this is t2  
T3 : this is t3  
Conclusion : Failure  
Name : first  
File name : first_3  
Year : 12  
etc  
etc  
etc  
T1 : this is t1  
T2 : this is t2  
T3 : this is t3  
Conclusion : Success 

依旧.....

我需要一个perl脚本,它给出了以下输出:

Naming  File_name  Year  Conclusion  Reason  
first   first_1    12    Success     this is t1, this is t2, this is t3    
first   first_2    13    Success     this is t1, this is t2, this is t3   
second  second_1   12    Failure     this is t1, this is t2, this is t3  
first   first_3    12    Success     this is t1, this is t2, this is t3 

2 个答案:

答案 0 :(得分:1)

以下是您需要的。它读取要从STDIN解析的文件。可以是任何其他行数。

#!/usr/bin/perl

use strict;

my $Naming = "";
my $File_name = "";
my $Year = "";
my @Reason = ();
my $Conclusion = "";

print "Naming\tFile_name\tYear\tConclusion\tReason\n";
while (my $line = <STDIN>) {
  $line =~ /Conclusion : (\w+)/ and do {
    $Conclusion = $1;

    print "$Naming\t$File_name\t$Year\t$Conclusion\t" . join(", ",@Reason) . "\n";
    $Naming = "";
    $File_name = "";
    $Year = "";
    @Reason = ();
    $Conclusion = "";
  };

  $line =~ /Name : (.*)/ and $Naming = $1;
  $line =~ /File name : (.*)/ and $File_name = $1;
  $line =~ /Year : (\d+)/ and $Year = $1;
  $line =~ /T\d : (.*)/ and push(@Reason,$1);
}

答案 1 :(得分:0)

您没有说明您遇到的问题。将流拆分为记录?这样就可以了:

my @buf;
while (<>) {
   if (@buf && /^Name :/) {
      process_record(@buf);
      @buf = ();
   }

   push @buf, $_;
}

process_record(@buf) if @buf;