Code:
$
$ # Example file
$ cat f0.example
col1,col2,col3,col4,col5
a1,a2,a3,a4,a5
b1,b2,b3,b4,b5
$
$ # File with shuffled columns
$ cat f0.shuffled
col5,col3,col2,col4,col1
a5,a3,a2,a4,a1
b5,b3,b2,b4,b1
c5,c3,c2,c4,c1
d5,d3,d2,d4,d1
e5,e3,e2,e4,e1
$
$ # Run the Perl script, passing the example file and shuffled data file.
$ # The script reshuffles the header and data of f0.shuffled so that
$ # it matches the order of the header columns of f0.example.
$ perl -lne 'if ($.==1 && $#ARGV == 0) {
for $k (split/,/) {$x{$k} = $i++}
} elsif ($.==1) {
for $k (split/,/) {push @a,$x{$k}; $b[$x{$k}] = $k}
print join ",",@b; @b=();
} elsif ($#ARGV == -1) {$i = 0;
for $k (split/,/) {$n = $a[$i]; $b[$n] = $k; $i++}
print join ",",@b; @b = ();
}
close ARGV if eof;
' f0.example f0.shuffled
col1,col2,col3,col4,col5
a1,a2,a3,a4,a5
b1,b2,b3,b4,b5
c1,c2,c3,c4,c5
d1,d2,d3,d4,d5
e1,e2,e3,e4,e5
$
$ # Another file with (differently) shuffled columns
$ cat f1.shuffled
col3,col5,col4,col1,col2
a3,a5,a4,a1,a2
b3,b5,b4,b1,b2
$
$ # Run the Perl script, passing the example file and shuffled data file.
$ # The script reshuffles the header and data of f1.shuffled so that
$ # it matches the order of the header columns of f0.example.
$ perl -lne 'if ($.==1 && $#ARGV == 0) {
for $k (split/,/) {$x{$k} = $i++}
} elsif ($.==1) {
for $k (split/,/) {push @a,$x{$k}; $b[$x{$k}] = $k}
print join ",",@b; @b=();
} elsif ($#ARGV == -1) {$i = 0;
for $k (split/,/) {$n = $a[$i]; $b[$n] = $k; $i++}
print join ",",@b; @b = ();
}
close ARGV if eof;
' f0.example f1.shuffled
col1,col2,col3,col4,col5
a1,a2,a3,a4,a5
b1,b2,b3,b4,b5
$
$
$