I have a file with contents

When I gave

$ sort -h -t. -k3,4 sort_test.txt

Couldn't understand why comes before I thought, since two fields are used for comparison, second field is used when there is a tie and it should work as normal sorting.


This sorts .23 after .3:

$ sort -h -t. -k3,3 -k4,4 sort_test.txt
  • Why ? Though I have given -h option – user3539 Feb 12 '15 at 4:04
  • 1
    When sorting over a range -k3,4, the option -h only applies to the first field. The remainder of the range is sorted alphabetically. When specifying -k3,3 -k4,4, the -h option applies to the first field in each range. (And, yes, this is bizarre counter-intuitive behavior.) – John1024 Feb 12 '15 at 4:07

In the case is better use -n instead -h option. But the main thing is possible expansion of . For my opinion some versions of sort operate -t arguments as regexp, so to be sure I'd offer to escape .

sort -nt\. -k3,4 sort_test.txt 

An understanding of why sort is behaving "weird"

since you are sorting from key 3 to key 4 sort will ignore all other fields

 sort -h -t. -k3,4 sort_test.txt

will result in

extracting keys 3 and 4 from your results will explain why sort places above


Hence, we see the reason why sort behaving the way it should...sorting from keys 1 to 4 will therefore get you the correct result.

sort -h -t. -k1,4 sort_test.txt
  • My problem is about why above – user3539 Feb 16 '15 at 3:23
  • @user3539, and Xorg: -h is a numeric compare -- you are in fact comparing the number 1.23 with the number 1.3; with -V you will obtain what you expect (see my solution) – JJoao Feb 19 '15 at 17:49
  • @JJoao..no need to argue...refer to sort man pages or this link:computerhope.com/unix/usort.htm – repzero Feb 19 '15 at 21:17

-n and -h activate numeric comparisons; in this situation when we say "k3,4", k3 will get a float point number (k3=1.23 < 1.3) and k4="".

With "-V" the behavior is better: version numbers 1.2 < 1.3 < 1.23.

sort  -t. -k3,4V

applied to


The same result will be obtain with:

sort -t. -k3V
sort -V -t. -k3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.