CLI tip 16: transpose tables
GNU datamash has plenty of nifty features for field based operations. Here's an example of transposing comma delimited data:
$ cat scores.csv
Name,Maths,Physics,Chemistry
Ith,100,100,100
Cy,97,98,95
Lin,78,83,80
Er,60,70,90
$ datamash -t, transpose <scores.csv
Name,Ith,Cy,Lin,Er
Maths,100,97,78,60
Physics,100,98,83,70
Chemistry,100,95,80,90
And here's an alternate solution using tr
, wc
and pr
:
# divide input into five parts and join them vertically
$ seq 10 | pr -5ts,
1,3,5,7,9
2,4,6,8,10
# tr converts input table into single field per line
# wc calculates number of rows and pr does the rest
$ tr ',' '\n' <scores.csv | pr -$(wc -l <scores.csv)ts,
Name,Ith,Cy,Lin,Er
Maths,100,97,78,60
Physics,100,98,83,70
Chemistry,100,95,80,90
See also unix.stackexchange: How to process an x-column text file to get a y-column one? for many more ways to deal with such problems.
Video demo:
See also my Linux Command Line Computing ebook.