我有一些包含以下数据的文件。
示例文件 1:
sitename1,2009-07-19,"A1",11975,17.23
sitename1,2009-07-19,"A2",11,0.02
sitename1,2009-07-20,"A1",2000,17.23
sitename1,2009-07-20,"A2",538,0.02
我想将第 4 列中的值与第 2 列和第 3 列映射,如下所示。
需要输出。
Site,Type,2009-07-19,2009-07-20
sitename1,"A1",11975,2000
sitename1,"A2",11,538
这是我到目前为止所尝试的:
#! /usr/bin/perl -w
use strict;
use warnings;
my $column_header=["Site,Type"];
my $position={};
my $last_position=0;
my $current_event=[];
my $events=[];
while (<STDIN>) {
my ($site,$date,$type,$value,$percent) = split /[,\n]/, $_;
my $event_key = $date;
if (not defined $position->{$event_key}) {
$last_position+=1;
$position->{$event_key}=$last_position;
push @$column_header,$event_key;
}
my $pos = $position->{$event_key};
if (defined $current_event->[$pos]) {
dumpEvent();
}
if (not defined $current_event->[0]) {
$current_event->[0]="$site,$type";
}
$current_event->[$pos]=$value;
}
dumpEvent();
my $order = [];
for (my $scan=0; $scan<scalar(@$column_header); $scan++) {
push @$order,$scan;
}
printLine($column_header);
map { printLine($_) } @$events;
sub printLine {
my $record=shift;
my @result=();
foreach my $offset (@$order) {
if (defined $record->[$offset]) {
push @result,$record->[$offset];
} else {
push @result,"";
}
}
print join(",",@result)."\n";
}
sub dumpEvent {
return unless defined $current_event->[0];
push @$events,$current_event;
$current_event=[];
}
我得到的输出如下。
*Site,Type,2009-07-19,2009-07-20*
sitename1,"A1",11975,
sitename1,"A2",11,
sitename1,"A1",,14620
sitename1,"A2",,538