Skip to content
Advertisement

Reasoning behind ‘sort’ core util’s key (-k) syntax

When using the sort function in a shell, it seems the preferred syntax for the -k option when sorting via only one field is, for example, -k5n,5. What’s the advantage of the ,5 in this case? -k5n works the same, or at least seems to for me.

Refs:

  1. The man page seems to prefer this but also suggests it is optional
  2. This answer seems to prefer this syntax too

Advertisement

Answer

Assume your data has N fields. -k5n is equivalent to -k5,Nn, meaning the data will be sorted using fields 5 through N as the key. This may not be desirable, for instance if you want a stable sort that doesn’t modify the relative order of records in the input with equal values for the 5th field. Using -k5,5n makes it explicit that you want to sort on the 5th field alone.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement