Outside of rolling a custom solution to transpose rows with columns from a command line the only tool I've ever seen that can do this is a tool called ironically transpose
.
Installation
Unfortunately it's not in any repo so you'll need to download and compile it. This is pretty straightforward since it has no additional libraries that it's dependent on. It can be accomplished like so:
$ gcc transpose.c -o transpose
Usage
It can handle straightforward text files with ease. For example:
$ cat simple.txt
X column1 column2 column3
row1 0 1 2
row2 3 4 5
row3 6 7 8
row4 9 10 11
Can be transposed using this command:
$ transpose -t --fsep " " simple.txt
X row1 row2 row3 row4
column1 0 3 6 9
column2 1 4 7 10
column3 2 5 8 11
This command is transpose
to transpose (-t
) and the field separator to use is a space (--fsep " "
).
Your example
Since your sample data is in a slightly more complex format it needs to be dealt with in 2 phases. First we need to translate it into a format that transpose
can deal with.
Running this command, will put the data in a more horizontally friendly format:
$ sed 's/:/ /; /^$/d' sample.txt \
| sort | paste - - - - -
title1 A1 title1 B1 title1 C1 title1 D1 title2 A2
title2 B2 title2 C2 title2 D2 title3 A3 title3 B3
title3 C3 title3 D3 title4 A4 title4 B4 title4 C4
title4 D4 title5 A5 title5 B5 title5 C5 title5 D5
Now we just need to remove the secondary occurrences of the title1, title2, etc.:
$ sed 's/:/ /; /^$/d' sample.txt \
| sort | paste - - - - - | sed 's/\ttitle[0-9] / /g'
title1 A1 B1 C1 D1 A2
title2 B2 C2 D2 A3 B3
title3 C3 D3 A4 B4 C4
title4 D4 A5 B5 C5 D5
It's now in a format that transpose
can deal with. The following command will do the entire transposition:
$ sed 's/:/ /; /^$/d' sample.txt \
| sort | paste - - - - - | sed 's/\ttitle[0-9] / /g' \
| transpose -t --fsep " "
title1 title2 title3 title4
A1 B2 C3 D4
B1 C2 D3 A5
C1 D2 A4 B5
D1 A3 B4 C5
A2 B3 C4 D5