1

I need to transpose a file from this format

1 2 3 4  
6 7 8 9   
a b c d   
f g h i j 

to this format

1 2 6 7 a b f g  
3 4 8 9 c d h k

two columns in a single row in the way posted above.

Any suggestions??

  • where is the k in your output coming from? – iruvar Jul 19 '13 at 18:20
3

Assuming that the k in your output is a typo, here is one way to do it in bash

paste -d $'\n' <(cut -f1,2 -d' ' input.txt | tr -s $'\n' ' ') \
<(cut -f3,4 -d' ' input.txt | tr -s $'\n' ' ')

which produces

1 2 6 7 a b f g 
3 4 8 9 c d h i

GNU awk-based solution

awk '{for (j = 1; j <= NF; ++j) arr[NR,j] = $j};
END{
  for (j=1; j <=NF; j+=2) for(i=1; i <=NR; ++i){
    printf i == 1?"": " "; printf arr[i,j]" "arr[i,j+1];
    if (i == NR) printf "\n"
  }
}' input.txt
  • Thank you very much. Any ideas how to apply it on a 1000 column file? – user43405 Jul 19 '13 at 19:13
  • 1
    @user43405 - you should either ask that as a 2nd question (independent of this) or edit this question with some "more" of that sample data. – slm Jul 19 '13 at 19:25
  • 1
    @user43405, I agree with slm, you should post a different question. FWIW, i have added a memory-intensive awk solution that should work for more than 4 columns. If you post a different question, you are likely to get better solutions than this from the experts on this forum – iruvar Jul 19 '13 at 20:33

Your Answer

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

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