Sort by first row - awk

how can i sort the table based on first row? thanks in advance

input

name    d       b       c       a
l       l1      l2      l3    l4
l1      1       2       3       4
l2      2       2       2       1
l3      1       1       2       2

ouput

name    a       b       c       d
l1     l4       l2      l3     l1
l1      4       2       3       1
l2      1       2       2       2
l3      2       1       2       1

This is not as easy as it seems in the first place. Given you spell "Name" with uppercase "N" and that "N" sorts below all lower case letters, you could try like

awk -f transp.awk file | LC_ALL=C sort | awk -f transp.awk
Name    a       b       c       d
l       l4      l2      l3      l1
l1      4       2       3       1
l2      1       2       2       2
l3      2       1       2       1

with transp.awk

                {MX=NF
                 for (i=1; i<=NF; i++) C[NR, i]=$i
                }
END             {for (j=1; j<=NR; j++)  {for (i=1; i<=MX; i++) printf "%s\t", C[i,j]
                                         printf "\n"
                                        }
                }

You may want to add some refinements, like setting MX to the max(NF), or doing some error checking... some awk versions offer their internal sort; that might help as well...

1 Like

Umm. sorry. It seems the script is transposing the table not sorting.

Yes it does. Did you consider reading the entire post and using the first line of my proposal, i.e. transpose - sort - transpose?

ok. thanks a lot.