1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#!/usr/bin/perl
die "Usage: cat file.txt | swapCols.pl $#ARGV cols1 cols2\nColumns are coma separated list of one-base column indexes\n" if $#ARGV < 1;
# Parse command line arguments
@cols1 = split /,/, $ARGV[0];
@cols2 = split /,/, $ARGV[1];
die "Different number of columns in each argument" if( $#cols1 != $#cols2 );
# Add indexes to swap
for($i = 0 ; $i <= $#cols1 ; $i++ ) {
$c1 = $cols1[$i] - 1;
$c2 = $cols2[$i] - 1;
$idx[$c2] = $c1;
$idx[$c1] = $c2;
}
# Process SDTIN
while( $l = <STDIN> ) {
chomp $l;
@t = split /\t/, $l;
for( $i = 0 ; $i <= $#t ; $i++ ) {
if( $i > 0 ) { print "\t"; }
$j = $idx[$i];
# Should we swap this one?
if( $j ne '' ) { print "$t[$j]"; }
else { print "$t[$i]"; }
}
print "\n";
}
|