Micha Niskin

Jul 6, 09:27 AM
Category  

Sometimes you have an input stream that you wish to sort, but you don’t necessarily want to sort on the entire line. Suppose you want to print out the /etc/passwd file with all the users orderd by UID, or something. Luckily, the sort(1) utility has an option for you to make it all simple and easy.

sort -t: -k3n /etc/passwd

The -t option sets the field delimiter (in this case it’s a colon), and the -k option selects which field to key on in the sort.

The -k option takes a parameter of the form F[.C][OPTS], where where F is the field number and C the (optional) character position in the field. OPTS is zero or more single-letter ordering options, which override global ordering options for that key (I used n in my example to sort according to string numerical value, but you can have more if you want, or none at all).

Comment