My script uses ${1+"$@"}
to supply file names on the awk command line
so that if no files are specified awk will read its standard input. This
is much better than plain $* which can't handle filenames containing
whitexspace.
#! /bin/sh
# Transpose a matrix: assumes all lines have same number
# of fields
exec awk '
NR == 1 {
n = NF
for (i = 1; i <= NF; i++)
row[i] = $i
next
}
{
if (NF > n)
n = NF
for (i = 1; i <= NF; i++)
row[i] = row[i] " " $i
}
END {
for (i = 1; i <= n; i++)
print row[i]
}' ${1+"$@"}
Here's a test file:
1 2 3 4
5 6 7 8
9 10 11 12
Now we run transpose on the file.
$ transpose test
1 5 9
2 6 10
3 7 11
4 8 12