Code:
$
$
$ # correct format
$ cat file
date,nomsgsent,nomsgnotdeliver,nomsgdelay
201003251000,1000,1,2
201003251000,900,0,0
201003251000,1450,0,0
201003251000,1230,0,0
$
$ # (1) missing "nomsgnotdeliver"
$ cat file1
date,nomsgsent,nomsgdelay
201003251000,1000,2
201003251000,900,0
201003251000,1450,0
201003251000,1230,0
$
$ # Perl script
$ ##
$ perl -lne 'BEGIN {%x=qw(date 0 nomsgsent 1 nomsgnotdeliver 2 nomsgdelay 3);
> %y=qw(0 date 1 nomsgsent 2 nomsgnotdeliver 3 nomsgdelay);
> $hdr="date,nomsgsent,nomsgnotdeliver,nomsgdelay"}
> chomp; @a = split/,/;
> if ($.==1) {
> foreach $i (@a) {delete $y{$x{$i}} if (defined $x{$i})}
> print $hdr;
> } else {
> foreach $k (keys %y) {$b[$k]=""}
> for ($i=0; $i<=$#a; $i++){
> $m=0;
> while (defined $b[$m]){$m++}
> $b[$m] = $a[$i];
> }
> print join(",",@b);
> @b=();
> }' file1
date,nomsgsent,nomsgnotdeliver,nomsgdelay
201003251000,1000,,2
201003251000,900,,0
201003251000,1450,,0
201003251000,1230,,0
$
$ # (2) missing "nomsgsent", "nomsgnotdeliver"
$ cat file2
date,nomsgdelay
201003251000,2
201003251000,0
201003251000,0
201003251000,0
$
$ # Perl script
$ ##
$ perl -lne 'BEGIN {%x=qw(date 0 nomsgsent 1 nomsgnotdeliver 2 nomsgdelay 3);
> %y=qw(0 date 1 nomsgsent 2 nomsgnotdeliver 3 nomsgdelay);
> $hdr="date,nomsgsent,nomsgnotdeliver,nomsgdelay"}
> chomp; @a = split/,/;
> if ($.==1) {
> foreach $i (@a) {delete $y{$x{$i}} if (defined $x{$i})}
> print $hdr;
> } else {
> foreach $k (keys %y) {$b[$k]=""}
> for ($i=0; $i<=$#a; $i++){
> $m=0;
> while (defined $b[$m]){$m++}
> $b[$m] = $a[$i];
> }
> print join(",",@b);
> @b=();
> }' file2
date,nomsgsent,nomsgnotdeliver,nomsgdelay
201003251000,,,2
201003251000,,,0
201003251000,,,0
201003251000,,,0
$
$
$ # (3) missing "date", "nomsgnotdeliver"
$ cat file3
nomsgsent,nomsgdelay
1000,2
900,0
1450,0
1230,0
$
$ # Perl script
$ ##
$ perl -lne 'BEGIN {%x=qw(date 0 nomsgsent 1 nomsgnotdeliver 2 nomsgdelay 3);
> %y=qw(0 date 1 nomsgsent 2 nomsgnotdeliver 3 nomsgdelay);
> $hdr="date,nomsgsent,nomsgnotdeliver,nomsgdelay"}
> chomp; @a = split/,/;
> if ($.==1) {
> foreach $i (@a) {delete $y{$x{$i}} if (defined $x{$i})}
> print $hdr;
> } else {
> foreach $k (keys %y) {$b[$k]=""}
> for ($i=0; $i<=$#a; $i++){
> $m=0;
> while (defined $b[$m]){$m++}
> $b[$m] = $a[$i];
> }
> print join(",",@b);
> @b=();
> }' file3
date,nomsgsent,nomsgnotdeliver,nomsgdelay
,1000,,2
,900,,0
,1450,,0
,1230,,0
$
$
$