Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

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.

share|improve this question

marked as duplicate by jw013, slm, Ramesh, Anthon, jasonwryan May 27 at 7:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers 2

up vote 0 down vote accepted

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

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

share|improve this answer

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
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.