An efficient way to transpose a file in Bash

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

    I've used below two scripts to do similar operations before. The first is in awk which is a lot faster than the second which is in "pure" bash. You might be able to adapt it to your own application.

    awk '
    {
        for (i = 1; i <= NF; i++) {
            s[i] = s[i]?s[i] FS $i:$i
        }
    }
    END {
        for (i in s) {
            print s[i]
        }
    }' file.txt
    
    declare -a arr
    
    while IFS= read -r line
    do
        i=0
        for word in $line
        do
            [[ ${arr[$i]} ]] && arr[$i]="${arr[$i]} $word" || arr[$i]=$word
            ((i++))
        done
    done < file.txt
    
    for ((i=0; i < ${#arr[@]}; i++))
    do
        echo ${arr[i]}
    done
    

提交回复
热议问题