I have a program which output looks like this

 #         Status   VAL1   VAL2   Description
 1      some text    2.5    4.4   Some long other text
 5    some text 2   14.5    2.0   Some long other text 2
12    some text 3  222.6   24.4   Some long other text 3
19    some text 4    3.4    1.5   Some long other text 4
21    some text 5   55.4   10.6   Some long other text 5
32    some text 6    2.9    9.4   Some long other text 6

I'd like to sort along the VAL2 column. I tried with sort -k 4 but when there's spaces in the Status column sort get confused.

Is there a way to work around this? Maybe to pass a character number instead of a field number?

  • Yes, that can be done, look up the -k option to sort(1). Just make sure the input file doesn't contain tabs, as they will throw off your count (expand(1)) – vonbrand Mar 4 '13 at 14:04
  • @vonbrand it won't work that way, cause sort will take any space sequence as field delimiter and you cannot predict which one will be on forth column. furthermore it won't be VAL2. – rush Mar 4 '13 at 14:23
  • @rush, just tell sort that the field delimiter is something impossible, and count characters in the first "field" (the full line). – vonbrand Mar 4 '13 at 14:25

Sort based on column offset:

sort -k1.27g

Note that the g flag above (for general numeric sorting) is not standard so may not be supported by your sort implementation.

With that particular data sample, you can get away with:

LC_ALL=C sort -k1.27

That is do an alphanumeric sort and use the C locale to make sure the leading spaces are not ignored in the sorting. So for instance [ ]4.4 sorts before 24.4 even though 4 sorts after 2.

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.