Difference of Sort -n -k2 -k3 & Sort -n -k2,3

Hi,

Could anyone kindly show me a link or explain the difference between

sort -n -k2 -k3 & sort -n -k2,3 

Also, if I like to remove the row with repetition at both $2 and $3, Can I safely use

sort -u -k2 -k3 

Example;

100 20 30
100 20 30

So, both $2 and $3 are same and I would like to have

100 20 30

Thanks,

According to the standards, the command:

sort -n -k2 -k3 file

sorts lines in file into increasing order evaluating field 2 and all fields following it as numeric values and if fields 2 to the end of the line compare equal to another line it then compares field 3 and all fields following it as numeric values and if two lines still compare as equal it then compares the entire line as a string of bytes to determine which line will come first.

sort -n -k2,3 file

sorts lines in file into increasing order evaluating the 2nd and 3rd fields as numeric values and if the numeric values of those two fields are the same when comparing two lines the entire line will be compared as a string of bytes to determine which line will come first.

If what you are trying to do is sort numeric values in fields 2 and 3 in file and only keep one line in cases when there are multiple lines with identical numeric values in those two fields, you would want to use:

sort -u -n -k2,3 file

if field 2 is your primary sort key and field 3 is your secondary key or:

sort -u -n -k3,3 -k2,2 file

if field 3 is your primary sort key and field 2 is your secondary key.

1 Like

I believe this would combine from the second to the third field as one sort key.

To achieve evaluating the 2nd and 3rd fields as separate numeric values, I think one would need:

sort -n -k2,2 -k3,3 file

Compare for example:

$ echo "1   2
2   3
2  2
2 1" | sort -n -k1,2
1   2
2   3
2  2
2 1

to

$ echo "1   2
2   3
2  2
2 1" | sort -n -k1,1 -k2,2
1   2
2 1
2  2
2   3
3 Likes