1

I have a file that I want to sort from the nth column (which is numeric) - not the nth field. The file looks schematically like:

1 Here are four words       9 8 5 
2 Here's two                7 2 6
3 One 2 3                  10 3 7
4 Guess how many are here   9 4 8
123456789012345678901234567890123

(where the last line is just a counter for clarity). The good folk at stackexchange showed me that i need something like sort -k1.27, which almost does what i want.

However, where there are ties initially (as in lines 1 and 4 above; both "9"), sort falls back to the start of the field, ranking line 1 before line 4 in this case (because "1" comes before "4"); whereas what i need is a sort starting at field 1.27 (i.e., one that ranks "9 4" before "9 8").

I've tried sort -g -k1.27,1.34 [and sort -g -k1.27,34] but the extra argument has no evident effect...any ideas?

4

You can define multiple sort keys:

sort -k1.27n -k1.30n

For ties the fall-back is a lexical comparison of the full lines.

sort -k 1.27,1.34 would define one key that consists of the portion of the line between the 27th and 34th character of the first field. However with -g, that tells sort to consider that key as numerical, so anything past the first non-digit would be ignored.

Note that with -k1.27, the key is defined as starting at the 27th character of the first field and ending at the end of the line. With n, only the initial numerical part is considered.

  • Thanks, Stephen...but if i understand you correctly, shouldn't my "solution" sort -g -k1.27,1.34 have worked (i.e., have sorted on columns 27:34)? – ionh Feb 26 '16 at 16:51
  • 1
    Sorry Stephen for hijacking your question, by now I should probably have added my own answer... – Stéphane Chazelas Feb 26 '16 at 16:56
  • Okay, i'm not sure who to thank now (and i think the answer above has been edited again?), but i'm still puzzled... Although the 'sort -k1.27 -k1.30' answer does work, if i read the responses correctly, then i'd've expected 'sort -g -k1.27' (sort using column 27 to end of line) and 'sort -g -k1.27,1.34' (sort using columns 27:34) to work...but they don't – ionh Feb 26 '16 at 17:06
  • 1
    @StéphaneChazelas no worries! – Stephen Kitt Feb 26 '16 at 17:08
  • @ionh The thing is that you need to define multiple keys here because numerical values stop at non-numeric characters. -k1.27 on its own or -k1.27,1.34 each define a single key, which only contains the first number – so on lines with ties, the second number isn't take into account. – Stephen Kitt Feb 26 '16 at 17:09

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.