não pode ... resistir ... ruído de linha ...
perl -F, -slE'if(@ARGV){say;@h=@F}elsif($.>1){$d{$F[0]}->@{@h}=($F[0],("null")x@h)unless$d{$F[0]};$d{$F[0]}{$F[1]}=$F[2]}close ARGV if eof}END{say$d{$_}->@{@h}for keys%d' -- -,=, file{1,2}.csv
ou um one-liner (um pouco) mais sensato
perl -F, -lane '
if (@ARGV) {print; @sources = @F[1..$#F]} # the first file
elsif ($. > 1) { # the 2nd file, minus the header
$data{$F[0]}->@{@sources} = ("null") x @sources unless $data{$F[0]};
$data{$F[0]}{$F[1]} = $F[2];
}
close ARGV if eof; # reset $. for each new file
} END {
$, = ",";
print $_, $data{$_}->@{@sources} for sort keys %data
' file1.csv file2.csv
ou, isso é "combine.pl"
#!/usr/bin/env perl
use v5.22;
use Path::Tiny; # convenience module from CPAN
# read the header from the first file
my $file = path("file1.csv");
my @lines = $file->lines;
my $header = $lines[0];
chomp $header;
my @sources = split /,/, $header;
# read the data from the second file
$file = path("file2.csv");
chomp( @lines = $file->lines );
shift @lines; # ignore the header
my %data;
for my $line (@lines) {
my ($id, $source, $value) = split /,/, $line, 3;
if (not exists $data{$id}) {
# initialize the output data for a new id
$data{$id}->@{ @sources } = ($id, ("null") x scalar(@sources));
}
# and store this value
$data{$id}{$source} = $value;
}
# output the results
say $header;
$, = ",";
for my $id (sort {$a <=> $b} keys %data) {
say $data{$id}->@{@sources};
}
então: perl combine.pl > output.csv