I have read Trying to sort on two fields, second then first. I am still confused.

In the man sort page:

KEYDEF  is  F[.C][OPTS][,F[.C][OPTS]] for start and stop position

Why there are two OPTS?

Does it mean you can write OPTS at any place? Or do the two OPTS affect different fields?

But isn't the key (e.g. -k3,5) function as a whole?

What will happen if the two OPTS are opposite? Such as:

sort -t " " -k3n,5nr filename

The other question is that -k3n,5nr contains two white-spaces, how can the shell translate that into a number?

When we want to compare multi fields, should we use multi -k (e.g. -k3 -k4 -k5)? Is -k3n,5n wrong?

  • Please give an example input and output of what it is you want to do in the "other question" part. For the first, from POSIX: "[options] shall have this effect if specified with field_start, field_end, or both." – muru Oct 10 '19 at 8:46
  • @muru solved in the Stephen Kitt answer below. – tranquil.coder Oct 10 '19 at 11:50
  • However, fields that extend to the end of the line, as -k 2, or fields consisting of a range, as -k 2,3, retain the field separators present between the endpoints of the range. the GNU sort manual – tranquil.coder Oct 10 '19 at 11:58

The sort specification describes this in a little more detail:

The 'b' modifier shall behave like the -b option, but shall apply only to the field_start or field_end to which it is attached. The other modifiers shall behave like the corresponding options, but shall apply only to the key field to which they are attached; they shall have this effect if specified with field_start, field_end, or both.

So you can add options in either position, and they apply to the whole key. They are cumulative, and I think the last one wins in case of conflict.

If you want to compare multiple numeric fields, you should specify them as separate keys; the GNU sort manual says

For the large majority of applications, treating keys spanning more than one field as numeric will not do what you expect.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.