Using bash to sort data horizontally

后端 未结 3 2133
执念已碎
执念已碎 2020-11-27 22:21

I have a file full of data in columns

sarah mark john
10    20   5
x     y    z 

I want to sort the data so the columns stay intact but the

3条回答
  •  孤街浪徒
    2020-11-27 23:26

    Coming from a duplicate question, this would sort the columns by the first row:

    #!/bin/bash
    
    input="$1"
    
    order=$((for i in $(head -1 $input); do echo $i; done) | nl | sort -k2 | cut -f1)
    
    grep ^ $input | (while read line
      do
        read -a columns <<< "${line%"${line##*[![:space:]]}"}"
    
        orderedline=()
        for i in ${order[@]}
        do
          orderedline+=("${columns[$i - 1]}")
        done
        line=$(printf "\t%s" "${orderedline[@]}")
        echo ${line:1}
      done)
    

    To sort by second row, replace head -1 $input with head -2 $input | tail -1. If the sort should be numeric, put in sort -n -k2 instead of sort -k2.

提交回复
热议问题