Terry
Terry

Reputation: 750

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 column 1 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 the following comment but it failed.

sort -n -k 1 -n -k 3

Upvotes: 7

Views: 13873

Answers (2)

GMichael
GMichael

Reputation: 2776

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.

Upvotes: 5

Double Sept
Double Sept

Reputation: 326

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

Upvotes: 5

Related Questions