Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

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
like image 513
Michael Avatar asked Oct 01 '15 11:10

Michael


1 Answers

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.

like image 175
chepner Avatar answered Sep 27 '22 18:09

chepner