I have a file that contains:1 1 1 1 text17 9 4 2 text22 2 0.5 0.7 text35 4 1 2 text4I want to sort it (output to the terminal) according to the maximum of the first two columns.expected output:1 1 1 1 text12 1 0.5 0.7 text35 4 1 2 text47 9 4 2 text2how can this be achieved? thanks!
sort by the maximum of the first two columns
scripting;terminal;sort
Your input file is:1 1 1 1 text17 9 4 2 text22 2 0.5 0.7 text35 4 1 2 text4With this input a simple sort will work:$ sort << EOF> 1 1 1 1 text1> 7 9 4 2 text2> 2 2 0.5 0.7 text3> 5 4 1 2 text4> EOF1 1 1 1 text12 2 0.5 0.7 text35 4 1 2 text47 9 4 2 text2If we amend the input to something like...$ cat test.txt1 3 1 1 text17 9 4 2 text22 1 0.5 0.7 text35 4 1 2 text4Then the input becomes challenging. A simple sort no longer works, and we can test other approaches:$ sort -k1,1n -k2,2n < test.txt1 3 1 1 text12 1 0.5 0.7 text35 4 1 2 text47 9 4 2 text2This isn't what we'd expect - The first two lines of output are reversed - the highest 1/2 column value in line 1 is 3, and the highest in line 2 is 2.The following appears to work, at least for the revised input file, but it's not pretty (my awk-fu is weak):$ awk '{ sorton=$1; if ($2>$1) { sorton=$2 }; print $1, $2, $3, $4, $5, sorton }' < test.txt | sort -k 6 | cut -d   -f 1-52 1 0.5 0.7 text31 3 1 1 text15 4 1 2 text47 9 4 2 text2@Nominal-Animal and @JJoao suggested refinements, resulting in:$ awk '{ k= $1>$2 ? $1: $2 ; print k, $0 }' test.txt | sort -g | cut -d ' ' -f 2-2 1 0.5 0.7 text31 3 1 1 text15 4 1 2 text47 9 4 2 text2(Feel free to edit this post to refine an awk solution.)