What does the k parameter do in the sort function (Linux Bash Scripting)?
KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a field number and C a character position in the field; both are origin 1, and the stop position defaults to the line's end. If neither -t nor -b is in effect, characters in a field are counted from the beginning of the preceding whitespace. OPTS is one or more single-letter ordering options [bdfgiMhnRrV], which override global ordering options for that key. If no key is given, use the entire line as the key.
An example input file:
123 233
214 176
341 325
sort on the first field:
sort -t' ' -k1 input
Gives:
123 233
214 176
341 325
The second field:
sort -t' ' -k2 input
Gives:
214 176
123 233
341 325
Second and third digits of the first field:
sort -t' ' -k1.2 input
Gives:
214 176
123 233
341 325
Last digit of the second field:
sort -t' ' -k2.3 input
Gives:
123 233
341 325
214 176
Related videos on Youtube
user2316667
Updated on September 15, 2022Comments
-
user2316667 over 1 year
From Linux manual: sort via a key; KEYDEF gives location and type.
I have no idea what that means but I saw it being used like this:
cut -f 2 *ptt | tail -n +4 | sort | uniq -c | sort -k1 -rn
And then again like this:
ls -1 *\.flv | sort -n -k1.2
-
Xiong Chiamiov over 6 yearsThe default (in coreutils 8.22 at least) is to split columns based on whitespace, not tabs.
-
northern-bradley over 4 yearsit might we worth clarifying that the OPTS are the sort command's "-" options e.g.
sort -k8rn,8
is equivalent tosort -r -n -k8,8
. it allows you to sort each key in a different way rather than globally for the entire sort command (it took me ages before i realised)