# Transpose a matrix using sed

I'm trying to 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.

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. • Any reason you are limiting the solution to sed? What about awk? – Yzmir Ramirez Nov 14, 2011 at 1:18 • Thanks for the link @Kristian I was unaware of the site. – potong Nov 14, 2011 at 1:22 • @Yzmir I'm sure there are many published solutions in other languages but I am trying to improve my understanding of sed. BTW @Dave this is not homework per se just personal curiosity. – potong Nov 14, 2011 at 1:26 • This is a better fit back on SO than here on cg Nov 14, 2011 at 8:24 • Dubious as a code review question, here we like code you can read. Nov 24, 2011 at 4:30 ## 1 Answer This yet another way to do it: sed -r '1{s/$/ /;s/ / \n/g};:a;$!N;s/$/ /;:b;s/\n(.*\n+)(\S+\s)/\2@!@\1/;tb;s/@!@/\n/g;${s/ \n/\n/g;s/\n+$//;q};ba'


This method is somewhat faster and only uses single delimiter which may be crafted to be unique. i.e. @!@ in this example