An efficient way to transpose a file in Bash

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

    Another bash variant

    $ cat file 
    XXXX    col1    col2    col3
    row1    0       1       2
    row2    3       4       5
    row3    6       7       8
    row4    9       10      11
    

    Script

    #!/bin/bash
    
    I=0
    while read line; do
        i=0
        for item in $line; { printf -v A$I[$i] $item; ((i++)); }
        ((I++))
    done < file
    indexes=$(seq 0 $i)
    
    for i in $indexes; {
        J=0
        while ((J

    Output

    $ ./test 
    XXXX    row1    row2    row3    row4    
    col1    0       3       6       9   
    col2    1       4       7       10  
    col3    2       5       8       11
    

提交回复
热议问题