sort --reverse does not reverse numeric sorts
Affects | Status | Importance | Assigned to | Milestone | |
---|---|---|---|---|---|
coreutils (Ubuntu) |
New
|
Undecided
|
Unassigned |
Bug Description
The --reverse option is supposed to reverse the sense of comparisons, but does not affect numeric ('g' or 'n') sorts.
With the input filed 02 q
l 10 f
abc 01 x
abc 01 y
abc 01 z
n 10 u
d 02 m
d 02 b
b 10 c
I get the same results with either of
sort --reverse -k2n
sort -k2n
namely
abc 01 x
abc 01 y
abc 01 z
d 02 b
d 02 m
d 02 q
b 10 c
l 10 f
n 10 u
But if I do
sort --reverse -k2
I get
n 10 u
l 10 f
b 10 c
d 02 q
d 02 m
d 02 b
abc 01 z
abc 01 y
abc 01 x
And the same things happen with or without leading zeroes on field 2.
ProblemType: Bug
DistroRelease: Ubuntu 14.04
Package: coreutils 8.21-1ubuntu5
ProcVersionSign
Uname: Linux 3.13.0-43-generic x86_64
ApportVersion: 2.14.1-0ubuntu3.6
Architecture: amd64
CurrentDesktop: XFCE
Date: Sat Dec 20 11:00:06 2014
InstallationDate: Installed on 2014-08-11 (131 days ago)
InstallationMedia: Xubuntu 14.04.1 LTS "Trusty Tahr" - Release amd64 (20140723)
SourcePackage: coreutils
UpgradeStatus: No upgrade log present (probably fresh install)
This is not a bug, but expected behaviour.
If an ordering option is supplied to '-k' ('n' in this particular case),
global ordering options are overridden.
I.e. when sort is called this way:
sort --reverse -k2
the global option '--reverse' takes effect.
But in this case:
sort --reverse -k2n
the '--reverse' option is overridden by 'n', therefore the command
becomes equivalent to:
sort -n -k2
The solution woud be to to either stick to global options:
sort --reverse --numeric-sort -k2
or if sorting options for multiple fields are required, to add a
local reverse option to '-k':
sort -k2rn
BTW: this behaviour is also documented in the man page: [,F[.C] [OPTS]] for start and stop position, where F is a field number and C a character position in the field; both are origin 1, and the stop position defaults to the line's
...
-k, --key=KEYDEF
sort via a key; KEYDEF gives location and type
...
KEYDEF is F[.C][OPTS]
end. If neither -t nor -b is in effect, characters in a field are counted from the beginning of the preceding whitespace. OPTS is one or more single-letter ordering options [bdfgiMhnRrV], which
override global ordering options for that key. If no key is given, use the entire line as the key.
...