An efficient way to transpose a file in Bash

前端 未结 29 2687
时光说笑
时光说笑 2020-11-22 03:30

I have a huge tab-separated file formatted like this

X column1 column2 column3
row1 0 1 2
row2 3 4 5
row3 6 7 8
row4 9 10 11

I would like t

29条回答
  •  情书的邮戳
    2020-11-22 03:51

    Here is a Bash one-liner that is based on simply converting each line to a column and paste-ing them together:

    echo '' > tmp1;  \
    cat m.txt | while read l ; \
                do    paste tmp1 <(echo $l | tr -s ' ' \\n) > tmp2; \
                      cp tmp2 tmp1; \
                done; \
    cat tmp1
    

    m.txt:

    0 1 2
    4 5 6
    7 8 9
    10 11 12
    
    1. creates tmp1 file so it's not empty.

    2. reads each line and transforms it into a column using tr

    3. pastes the new column to the tmp1 file

    4. copies result back into tmp1.

    PS: I really wanted to use io-descriptors but couldn't get them to work.

提交回复
热议问题