1

I am trying to sort a file that contains entries like this.

This is the output of head file.txt | sort -n

1       1       360030.650313113        23.6496749206273
1       2       184005.303709890        12.5819130584254
1       3       51304.4897339131        3.54834660232693
2       1       184005.303709890        12.5819130584254
2       2       176030.554401950        13.7621056226822
2       3       71841.9750474998        6.31576927490416
3       1       51304.4897339131        3.54834660232693
3       2       71841.9750474998        6.31576927490416
3       3       72642.2936524586        9.28260169486644
4       1       12511.6549282967        0.867004812539363

And this is the output of cat file.txt | sort -n | head

1       100     0.265986106008280       1.948706529813553E-005
1       1000    3.184914160835964E-004  3.067021647295356E-008
1       1001    7.604450718679718E-005  7.326181191420022E-009
1       1002    1.809620185415599E-005  1.743513966528432E-009
1       1003    4.304204593193070E-006  4.147009800188772E-010
1       1004    1.023686141641656E-006  9.863012681974230E-011
1       1005    2.434647501464963E-007  2.345735005737759E-011
1       1006    5.790348098792519E-008  5.578886733501962E-012
1       1007    1.377124338943865E-008  1.326832274761822E-012
1       1008    3.275228617666499E-009  3.155618499463635E-013

As you can see, if I only use a small portion of the file, the output is sorted exactly the way I want, but when I use the whole file, somehow 100 comes before 1. I tried specifying -k1,2 and also -k1n,2n to no avail.

What can I do to have the whole file sorted like 1,1; 1,2; 1,3 ... 1,2000; 2,1; 2,2; ... 2,2000; etc?

My sort version is sort (GNU coreutils) 8.21, if that should be relevant.

2

You can move through field by field:

sort -k1,1n -k2,2n -k3,3n -k4,4n file.txt

This will sort numerically according to the 1st field first, if the fields are same for more than one line then they will be sorted according to the 2nd field and so on up to the last. You can modify the order to fit your need.

4
  • Thanks, that works. But do you know why just the -n switch doesn't work? I thought that that would switch the sort to numerical sort globally, and it would go through one field after the other if nothing else is specified
    – fifaltra
    Dec 8 '15 at 4:49
  • @fifaltra that would sort numerically but the whole line is taken is the key leading to the unwanted behavior..
    – heemayl
    Dec 8 '15 at 4:54
  • 1
    @fifaltra: It is not global. It is leading number according to LC_NUMERIC, LC_CTYPE. Test with --debug.
    – Runium
    Dec 8 '15 at 6:55
  • You could test sort -k1n -k2n file, sort -nk1 -k2, sort -k1,1n -k2,2n file etc.
    – Runium
    Dec 8 '15 at 7:03

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.