An efficient way to transpose a file in Bash

前端 未结 29 2145
时光说笑
时光说笑 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:43

    A Python solution:

    python -c "import sys; print('\n'.join(' '.join(c) for c in zip(*(l.split() for l in sys.stdin.readlines() if l.strip()))))" < input > output
    

    The above is based on the following:

    import sys
    
    for c in zip(*(l.split() for l in sys.stdin.readlines() if l.strip())):
        print(' '.join(c))
    

    This code does assume that every line has the same number of columns (no padding is performed).

提交回复
热议问题