An efficient way to transpose a file in Bash

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

    Pure BASH, no additional process. A nice exercise:

    declare -a array=( )                      # we build a 1-D-array
    
    read -a line < "$1"                       # read the headline
    
    COLS=${#line[@]}                          # save number of columns
    
    index=0
    while read -a line ; do
        for (( COUNTER=0; COUNTER<${#line[@]}; COUNTER++ )); do
            array[$index]=${line[$COUNTER]}
            ((index++))
        done
    done < "$1"
    
    for (( ROW = 0; ROW < COLS; ROW++ )); do
      for (( COUNTER = ROW; COUNTER < ${#array[@]}; COUNTER += COLS )); do
        printf "%s\t" ${array[$COUNTER]}
      done
      printf "\n" 
    done
    

提交回复
热议问题