0

I have a big file with numbers like:

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

I want to tranpose it into

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

I have search on google for solutions, but those solutions simply don't work in my case.

  • Try http://unix.stackexchange.com/q/79642/9537, and http://stackoverflow.com/q/1729824/855954 – jw013 May 27 '14 at 01:28

2 Answers2

0

This solution should work for you.

awk '
{ 
    for (i=1; i<=NF; i++)  {
        a[NR,i] = $i
    }
}
NF>p { p = NF }
END {    
    for(j=1; j<=p; j++) {
        str=a[1,j]
        for(i=2; i<=NR; i++){
            str=str" "a[i,j];
        }
        print str
    }
}' file

TESTING

cat file

1 2 3 4
5 6 7 8
9 0 1 11

After running the above command, the output is,

1 5 9
2 6 0
3 7 1
4 8 11

REFERENCES

https://stackoverflow.com/questions/1729824/transpose-a-file-in-bash

Ramesh
  • 39,297
0

If you can use perl:

$ perl -anle '
    $l[$_] .= $F[$_] for 0..$#F;
    END {
        print join " ", split // for @l;
    }' file
1 5 9
2 6 9
3 7 9
4 8 9

or using unpack:

$ perl -nle '
    $i = 0;
    $l[$i++] .= $_ for unpack "(A2)*";
    END {
        print join " ", split // for @l;
    }' file
1 5 9
2 6 9
3 7 9
4 8 9
cuonglm
  • 153,898