6

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 ?

GMichael
  • 2,726
  • 1
  • 20
  • 30
Terry
  • 700
  • 2
  • 8
  • 17

2 Answers2

5

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

Community
  • 1
  • 1
Double Sept
  • 154
  • 1
  • 10
4

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.

SLePort
  • 15,211
  • 3
  • 34
  • 44
GMichael
  • 2,726
  • 1
  • 20
  • 30
  • Although this code may help to solve the problem, it doesn't explain _why_ and/or _how_ it answers the question. Providing this additional context would significantly improve its long-term educational value. Please [edit] your answer to add explanation, including what limitations and assumptions apply. – Toby Speight Aug 29 '16 at 13:44
  • Thanks for the editing. I do not think that it was required, though, as OP knew those flags (you can see them in the question). The point was is the arrangement of them. – GMichael Aug 30 '16 at 07:14