Skip to main content
3 of 4
edited tags
sepp2k
  • 9k
  • 2
  • 39
  • 51

Transpose a matrix using sed

Transpose the following data from:

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

to:

1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9
10 10 10 10 10 10 10 10 10 10

using sed only please. Shortest wins.

I have a working solution but I'm sure it can be improved:

sed -rn 'H;${x;s/\n/ &/g;s/$/@/;:a;s/\n([^ ]+ ?)(.*@.*)/%\2\1/;ta;s/ %+@//p;t;s/ *$/\n/;y/%/\n/;ta}'

It uses % and @ for newline and end-of-string delimiters which may be problematic. Lastly, I hope answering my own question is not considered bad form.

potong