Stephopolis
Stephopolis

Reputation: 1795

Sorting within a file by columns Linux

So I have seen lots of sort questions on here and I was hoping that someone could clear up my own. I have a file that looks like this:

data    dd  0.0 96  157 KL  71  X   6947
data    fb  0.0 11  3R2 HD  13  1   1850
data    bx  0.0 14  352 FG  12  X   4810
data    bh  0.0 13  3GF FH  1T  1   6840
data    fb  0.0 11  3R2 HD  13  1   1325
etc.

I want to sort the file by the 8th and 9th rows so that the output is this:

data    bx  0.0 14  352 FG  12  X   4810
data    dd  0.0 96  157 KL  71  X   6947
data    fb  0.0 11  3R2 HD  13  1   1325
data    fb  0.0 11  3R2 HD  13  1   1850
data    bh  0.0 13  3GF FH  1T  1   6840
etc.

I have tried

sort -n -k7 -k8 file > newfile

But that sorts it only this much:

data    dd  0.0 96  157 KL  71  X   6947
data    bx  0.0 14  352 FG  12  X   4810
data    fb  0.0 11  3R2 HD  13  1   1850
data    bh  0.0 13  3GF FH  1T  1   6840
data    fb  0.0 11  3R2 HD  13  1   1325
etc. 

So I tried:

> sort -n -k8 -k9 file > newfile

But that just makes it worse

data    dd  0.0 96  157 ZL  71  P   69412217
data    fb  0.0 11  3R2 HX  13  1   185135150
data    bx  0.0 14  352 FG  12  X   4810
data    bh  0.0 13  3GF FH  1T  1   6840
data    fb  0.0 11  3R2 HY  13  L   132321355
etc.

I did also try:

sort -n -k8,9 file > newfile

But that didn't seem to be reliable because it would do several correctly in a row, but then throw in some random guys:

data    dd  0.0 96  157 KL  71  X   6947
data    bx  0.0 14  352 FG  12  26  443810
data    fb  0.0 11  3R2 HD  13  1   1850
data    bh  0.0 13  3GF FH  1T  1   6840
data    bx  0.0 14  352 FG  12  2   465310
data    fb  0.0 11  3R2 HD  13  1   1325
etc. 

What is it that I am doing wrong here?

Upvotes: 1

Views: 250

Answers (1)

cnicutar
cnicutar

Reputation: 182619

How about this:

[cnicutar@ariel ~]$ sort -n -k8,8 -k9,9  tos

data    bx  0.0 14  352 FG  12  X   4810
data    dd  0.0 96  157 KL  71  X   6947
data    fb  0.0 11  3R2 HD  13  1   1325
data    fb  0.0 11  3R2 HD  13  1   1850
data    bh  0.0 13  3GF FH  1T  1   6840

This specifies the eighth field as primary key and the 9th as secondary.

Upvotes: 2

Related Questions