This uses of arrays of arrays which is a gawk extension:
tp(){ awk '{for(i=1;i<=NF;i++)a[i][NR]=$i}END{for(i in a)for(j in a[i])printf"%s"(j==NR?"\n":FS),a[i][j]}' "FS=${1-$'\t'}";}
Another option is to use rs
(which is a BSD utility that also comes with macOS):
$ cat /tmp/a
n A B C D
1 01 02 01 01
2 02 02 01 01
$ rs -c' ' -C' ' -T</tmp/a|sed 's/.$//'
n 1 2
A 01 02
B 02 02
C 01 01
D 01 01
-c
changes the input column separator, -C
changes the output column separator, and -T
transposes rows and columns.
When an output column separator is specified using -C
, an extra column separator character is added to the end of each output line, but you can remove it with sed 's/.$//'
:
$ seq 4|paste -d, - -|rs -c, -C, -T
1,3,
2,4,
$ seq 4|paste -d, - -|rs -c, -C, -T|sed 's/.$//'
1,3
2,4
The rs
command fails in the case where the first line ends with one or more empty columns, because the number of columns is determined based on the number of columns on the first line:
$ rs -c, -C, -T<<<$'1,\n3,4'
1,3,4,