page

Oct 14, 2019

transpose a file with awk

https://stackoverflow.com/questions/1729824/an-efficient-way-to-transpose-a-file-in-bash

Q. transpose a file

X column1 column2 column3
row1 0 1 2
row2 3 4 5
row3 6 7 8
row4 9 10 11

to

X row1 row2 row3 row4
column1 0 3 6 9
column2 1 4 7 10
column3 2 5 8 11
 
A.
 
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" "a[i,j]; # check FS (ex: space, tab, etc)
        }
        print str
    }
}' file

 

No comments:

Post a Comment