Code:
$
$ cat inputfile
Time,A,Server1,KPI1,data1
Time,A,Server1,KPI2,data2
Time,A,Server1,KPI3,data3
Time,A,Server1,KPI4,data4
Time,A,Server1,KPI5,data5
Time,A,Server2,KPI1,data6
Time,A,Server2,KPI2,data7
Time,A,Server2,KPI3,data8
Time,A,Server2,KPI4,data9
Time,A,Server2,KPI5,data10
Time,A,Server3,KPI1,data11
Time,A,Server3,KPI2,data12
Time,A,Server3,KPI3,data13
Time,A,Server3,KPI4,data14
Time,A,Server3,KPI5,data15
Time,A,Server4,KPI1,data16
Time,A,Server4,KPI2,data17
Time,A,Server4,KPI3,data18
Time,A,Server4,KPI4,data19
Time,A,Server4,KPI5,data20
$
$ perl -F, -lane 'BEGIN { @occurrences = (2, 4, 5);
$prefix = "Time";
%active = map {$_ => 1} @occurrences;
$header = join ",", ($prefix, map {"KPI".$_} @occurrences);
}
if ($F[2] ne $prev) {
$counter = 1;
if ($output) {print FH $output}
open(FH, ">", $F[2].".csv");
print FH $header;
$output = $prefix;
} elsif ($active{$counter}) {
$output .= ",".$F[4];
}
$prev = $F[2];
$counter++;
END {print FH $output}
' inputfile
$
$ find . -name "*.csv"
./Server2.csv
./Server3.csv
./Server4.csv
./Server1.csv
$
$ cat Server1.csv
Time,KPI2,KPI4,KPI5
Time,data2,data4,data5
$
$ cat Server2.csv
Time,KPI2,KPI4,KPI5
Time,data7,data9,data10
$
$ cat Server3.csv
Time,KPI2,KPI4,KPI5
Time,data12,data14,data15
$
$ cat Server4.csv
Time,KPI2,KPI4,KPI5
Time,data17,data19,data20
$
$