Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

6
  • @forcefsck: I don't think it's possible with only sort -k. The begfield function in GNU sort just counts down to zero. Your decorate-sort-undecorate (DSU) approach seems to be the best way I think. Commented Apr 2, 2011 at 23:20
  • Out of interest, why $NF,$RS and not $NF,$0? I didn't know $RS did that. (I guess it's equivalent to $NF,$"\n", which does the same, but that's also surprising I think.) Commented Apr 3, 2011 at 0:36
  • 2
    @johnny8888, @forcefsck: In awk, $ can be followed by any expression. “The effect of the field number expression evaluating to anything other than a non-negative integer is unspecified”. GNU awk (on my system) treats a string like "\n" as zero. Others (e.g. the original implementation by A, W and K) abort with an error message. If RS happened to be a digit, you'd get the corresponding field on any implementation. So don't do this, use $0. Commented Apr 3, 2011 at 11:51
  • 2
    Really neat! So the long explanation of what is going on: with awk, print the last field first then the whole record, sort in reverse numerically, then trim off the first column using cut. Commented Nov 7, 2016 at 15:00
  • 2
    The method used here is called Schwartzian transform. Commented Nov 23, 2021 at 20:48