This can be done in pure awk , but as @steve said, it is not perfect. gawk has limited sorting functions, and awk does not have built-in sorting. However, here is a (rather hacky) solution using the comparison function in gawk :
[ ghoti@pc ~/tmp3]$ cat text 1 af 1 12 v 2 bg 2 10 w 3 ch 3 19 x 4 di 4 15 y 5 ej 5 11 z [ ghoti@pc ~/tmp3]$ cat doit.gawk Left-hand-side and right-hand-side, are sorted differently. { lhs[NR]=sprintf("%s %s %s",$1,$2,$3); rhs[NR]=sprintf("%s %s %s",$4,$5,$6); } END { asort(rhs,sorted,"cmp"); Step through the arrays and reassemble. printf("%s %s\n",lhs[i],sorted[i]); } } [ ghoti@pc ~/tmp3]$ gawk -f doit.gawk text 1 af 2 10 w 2 bg 5 11 z 3 ch 1 12 v 4 di 4 15 y 5 ej 3 19 x [ ghoti@pc ~/tmp3]$
This saves your entire input file in arrays so that lines can be collected after sorting. If your input is millions of lines, this can be problematic.
Note that you can play with printf and sprintf to set the appropriate output field separators.
You can find documentation on using asort() with functions on the gawk man page; find PROCINFO["sorted_in"] .
source share