Home > Mobile >  Sort by multiple conditions ascending and descending in bash
Sort by multiple conditions ascending and descending in bash

Time:11-07

I have a following issue. I have a file containg name,surname,age,mood. I need to sort this file by age (descending). If age is the same that sort it my surname (ascending). I use this: cat $FILE |sort -r -n -t"," -k3,3 -k2,2 > "$HOME"/people.txt But -r sorts both descending. How can I sort by surname ascending, please?

CodePudding user response:

By default sort will perform the sort in ascending order, the -r flag will perform the sort in descending order; the -r flag can be applied to individual -k directives when you need to use a mix of ascending and descending, eg:

$ cat raw.dat
1,2,4,5
1,2,7,5
1,2,9,5
1,2,3,5
1,3,7,5
1,1,7,5

Sort by column #3 (descending) and then column #2 (ascending):

$ sort -t"," -k3nr -k2n raw.dat
1,2,9,5
1,1,7,5
1,2,7,5
1,3,7,5
1,2,4,5
1,2,3,5

NOTES:

  • thanks to Ted Lyngmo for adding the n flag to properly handle numerics
  • if data could contain a mix of characters and numerics the n may need to be replaced depending on desired sort method (eg, V)
  • key takeaway is that quite a few of the sort flags can be applied at the -key level
  •  Tags:  
  • bash
  • Related