4
\$\begingroup\$

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.

\$\endgroup\$

migrated from codegolf.stackexchange.com Nov 20 '11 at 22:23

This question came from our site for programming puzzle enthusiasts and code golfers.

  • \$\begingroup\$ Any reason you are limiting the solution to sed? What about awk? \$\endgroup\$ – Yzmir Ramirez Nov 14 '11 at 1:18
  • \$\begingroup\$ Thanks for the link @Kristian I was unaware of the site. \$\endgroup\$ – potong Nov 14 '11 at 1:22
  • \$\begingroup\$ @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. \$\endgroup\$ – potong Nov 14 '11 at 1:26
  • 4
    \$\begingroup\$ This is a better fit back on SO than here on cg \$\endgroup\$ – Peter Taylor Nov 14 '11 at 8:24
  • 4
    \$\begingroup\$ Dubious as a code review question, here we like code you can read. \$\endgroup\$ – Winston Ewert Nov 24 '11 at 4:30
2
\$\begingroup\$

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy