How to transfer the data of columns to rows (with awk)?

mahmood picture mahmood · Mar 2, 2012 · Viewed 24.2k times · Source

I have a file like this:

n A B C D 
1 01 02 01 01
2 02 02 01 01

and I want to transfer the columns by rows, so the output should be like this:

n 1 2
A 01 02
B 02 02
C 01 01 
D 01 01

I have wrote this command:

awk '{ for (i=1;i<=NF;i++ ) printf $i " " }' file.txt > out-file.txt

the problem is that this command put everything on one line! so the output is like this:

n 1 2 A 01 02 B 02 02 C 01 01 D 01 01

Answer

Zsolt Botykai picture Zsolt Botykai · Mar 2, 2012

This might work:

awk '{
       for (f = 1; f <= NF; f++) { a[NR, f] = $f } 
     }
     NF > nf { nf = NF }
     END {
       for (f = 1; f <= nf; f++) {
           for (r = 1; r <= NR; r++) {
               printf a[r, f] (r==NR ? RS : FS)
           }
       }
    }' YOURINPUT

See it in action @ Ideone.