2

I'm having an issue sorting a file (badsort.small) containing these lines:

0 foo 30
0 foo/bar 26
0 foo/bar 2b
0 foo/bar 30
0 foo/bar 73
0 foo/bar 91
0 foo/bar d3

The following sort gives odd results:

sort -nk1,1 -k2,2 -k3,3 badsort.small

0 foo/bar d3
0 foo/bar 2b
0 foo/bar 26
0 foo 30
0 foo/bar 30
0 foo/bar 73
0 foo/bar 91

which is equivalent to sort -nk3,3. These commands sort correctly:

  • sort -k1,1 -k2,2 -k3,3
  • sort -nk1,1 -k2,3
  • sort -k2,2 -k3,3

What is it about this request that causes the wrong argument to turn numeric and prevail? Is there a way to avoid it? I'm generating sort args programmatically and though I can combine adjacent fields in this case I'm not confident I won't run into this again.

Reproduced on linux 3.2.0-70-generic and on osx 10.9.5.

2 Answers2

2

The -n is an overall program option, not part of any key descriptor, even when you physically combine it with a key descriptor in the way you did. If you want only the first key to be sorted numerically, then that would be

sort -k1,1n -k2,2 -k3,3

which in fact yields the same order that the input already is in.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

The option for numeric sorting would not take care of hexadecimal representation and would work on the string representation of the hexadecimal number. As John mentioned, you need to place the "n" option on the field that you would like to sort numerically.

If you would like to sort the hex field numerically:

sort hex numbers of different length from the command line?

Community
  • 1
  • 1
Khanna111
  • 3,627
  • 1
  • 23
  • 25