3

I have a file of three columns:

1   A     0.5
2   B     0.7
3   A     10
4   C     4
5   B     4

I want to sort the file by increasing order of column 3 and group by column 2

1  A   0.5
3  A   10
2  B   0.7
5  B   4
4  C   4

I know how to sort only based on the 3rd column :

sort -k3,3 file 

But can we group by the second column ?

  • 3
    What do mean when you say "group"? Do you need to retain field 2 file order? If not sort -k2,2 -k3,3n file should do – iruvar May 20 '15 at 12:27
  • yes your command does what I want thanks you can add the answer @1_CR – AWRAM May 20 '15 at 12:31
1

sort by the third column, then by the second:

$ sort -k3,3 file | sort -k 2,2

output:

1   A   0.5
3   A   10
2   B   0.7
5   B   4
4   C   4
0

I see there is no answer, so my suggestion

sort -k2,2 -nk3,3 file
  • n before k in -nk3,3 is a global option (equivalent to -n -k3,3), which makes the second column sort fail. You should use -k3,3n (or -k3n,3) instead. – Nicolas Melay Jul 30 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.