Search code examples
sortingunixawkcut

Sort values and output the indices of their sorted columns


I've got a file that looks like:

20 30 40
80 70 60
50 30 40

Each column represents a procedure. I want to know how the procedures did for each row. My ideal output would be

3 2 1
1 2 3
1 3 2

i.e. in row 1, the third column had the highest value, followed by the second, then the first smallest (this can be reversed, doesn't matter).

How would I do this?


Solution

  • I'd do it with some other Unix tools (read, cat, sort, cut, tr, sed, and bash of course):

    while read line
    do
      cat -n <(echo "$line" | sed 's/ /\n/g') | sort -r -k +2 | cut -f1 | tr '\n' ' '
      echo
    done < input.txt
    

    The output looks like this:

     3      2      1 
     1      2      3 
     1      3      2