Aakash Gupta
Aakash Gupta

Reputation: 31

Bash sorting comma delimited columns numerically and then alphabetically

I'm trying to sort 3 columns numerically in reverse (descending) by the third column first and then sort by the first column alphabetically (to break ties). Entries are delimited by commas(,).

For example, my dataset is:

y,5,50
x,10,50
z,4,100

Expected output:

z,4,100
x,10,50
y,5,50

However the output I am getting is:

z,4,100
y,5,50
x,10,50

I am using:

sort -t, -k3,3 -n -r -k1,1 filename

Not sure why this is not working.

Upvotes: 2

Views: 1013

Answers (2)

forumulator
forumulator

Reputation: 875

The reason what you're suggesting doesn't work is becuase you've applied the flags -n, -r globally hence the alphabetical sorting is also -reversed. To apply the flag on a per key basis, use:

sort -t, -k3,3nr -k1,1 filename

This gives the expected output:

z,4,100  
x,10,50  
y,5,50

Upvotes: 1

Cyrus
Cyrus

Reputation: 88583

I suggest to replace -k3,3 -n -r by -k3,3nr:

sort -t, -k3,3nr -k1,1 file

Output:

z,4,100
x,10,50
y,5,50

Upvotes: 3

Related Questions