Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux shell, sort column 1 in ascending order column 3 in descending order

my file contains 3 columns numbers, like 5 lines data below,

1 811036 395
2 811036 195
1 811036 295
2 811036 95
1 811036 95

I want to sort 1 column in ascending order and column 3 in descending order,

1 811036 395
1 811036 295
1 811036 95
2 811036 195
2 811036 95

I tried "sort -n -k 1 -n -k 3" but failed. how to write a single Linux shell command to accomplish this ?

like image 917
Terry Avatar asked Aug 29 '16 10:08

Terry


2 Answers

Please try this:

 sort -k1n -k3rn

Explanation:

-k# option: to specify the column used as a key for sorting.

-n: compares according to string numerical value.

-r : reverse the sorting order for specified key.

like image 30
GMichael Avatar answered Nov 15 '22 03:11

GMichael


The command sort -k1,1n -k3,3nr should work. It sorts only regarding column one (That's the difference between -k1 and -k1,1) so it can reach the second argument.

Note that sort -k1,1n -k3nr probably works too.

For more about multiple key sorting : Sorting multiple keys with Unix sort or https://unix.stackexchange.com/questions/52762/trying-to-sort-on-two-fields-second-then-first

like image 119
Double Sept Avatar answered Nov 15 '22 04:11

Double Sept