3

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?

Stephen Kitt
  • 434,908
  • 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 08: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

1 Answers1

3

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.

Stephen Kitt
  • 434,908
  • So, you mean that I cannot give 2 different options - one to start field and one to end field ? When I run sudo ls -l /etc | head -n 10 | sort -k 5n,6M I am getting error - sort: options '-Mn' are incompatible. – Number945 Jan 29 '21 at 18:05
  • 2
    -k defines one sort key, and a key can only be used to sort one way — so you can sort numerically and by month. But you can define multiple sort keys: -k5,5n -k6,6M. – Stephen Kitt Jan 29 '21 at 19:48