user1495523
user1495523

Reputation: 505

unix sort on multiple columns

I need to sort a table based on two columns, one column is numerical and while other is string. I need to have descending order for numerical while I would like to have alphabetical for string. Use of '-r' option for sort does work for numerical but it gets applied for sting too. I wonder how to apply reverse option only for one column and not the other.

Cmd: sort -r -k5 -k3 -k1

Data: Input

 il ||     2 |      3 ||
 we ||     2 |      2 ||
 dt ||     0 |      2 ||
 di ||     0 |      2 ||
 cs ||    16 |      1 ||
 fd ||     5 |      1 ||
 df ||    14 |      0 ||
 np ||     9 |      0 ||
 dt ||     9 |      0 ||
 ta ||     0 |      0 ||
 rt ||     0 |      0 ||
 ps ||     0 |      0 ||

Expected

 il ||     2 |      3 ||
 we ||     2 |      2 ||
 di ||     0 |      2 ||
 dt ||     0 |      2 ||
 cs ||    16 |      1 ||
 fd ||     5 |      1 ||
 df ||    14 |      0 ||
 dt ||     9 |      0 ||
 np ||     9 |      0 ||
 ps ||     0 |      0 ||
 rt ||     0 |      0 ||
 ta ||     0 |      0 ||

Upvotes: 0

Views: 231

Answers (1)

mathB
mathB

Reputation: 634

This works for me

$ sort -rk5 -k3 -k1b input

Output:

 il ||     2 |      3 ||
 we ||     2 |      2 ||
 di ||     0 |      2 ||
 dt ||     0 |      2 ||
 cs ||    16 |      1 ||
 fd ||     5 |      1 ||
 df ||    14 |      0 ||
 dt ||     9 |      0 ||
 np ||     9 |      0 ||
 ps ||     0 |      0 ||
 rt ||     0 |      0 ||
 ta ||     0 |      0 ||

Upvotes: 1

Related Questions