awk to transpose (super fast)

Credit goes to Stack Overflow - Transpose a file in bash. I was looking for a fast way to transpose a tab separated variable file, file.tsv, and so per instructions, I created the following shell script, transpose.sh:
#! /bin/bash
awk '
{ 
    for (i=1; i<=NF; i++)  {
        a[NR,i] = $i
    }
}
NF>p { p = NF }
END {    
    for(j=1; j<=p; j++) {
        str=a[1,j] 
        for(i=2; i<=NR; i++){
            str=str"\t"a[i,j]; 
            # delimitting variable can be replaced (i.e "," or " " or "\t")
        }
        print str
    }
}' file.tsv

Then, I ran transpose.sh through the command line and printed the transposed file.tsv to transpose_file.tsv
 transpose.sh > tr_file.tsv

Comments

Popular Posts