Sort question

Have a text file containing 4 columns, the 4th column is sorted numerically in descending order. The 2nd column is alpha text. Been able to get the 4th column to sort in descending order. The 2nd column sorts correctly but it's also in reverse. Would like to be able to keep the 4th column sort numerically descending while the 2nd column is sorted a-z, not z-a. This is what I have and can't seem to get it to work because everything is reversed.

sort -k2 -k4 -r file

this is what I'm trying to get:

xxxx apples xxxx 100
xxxx apples xxxx 90
xxxx oranges xxxx 80
xxxx oranges xxxx 70
xxxx pears xxxx 100
xxxx pears xxxx 90

this is what I'm getting because everything is reversed:

xxxx pears xxxx 100
xxxx pears xxxx 90
xxxx oranges xxxx 80
xxxx oranges xxxx 70
xxxx apples xxxx 100
xxxx apples xxxx 90

I'm sure this is simple but just can't get it to work.

sort -k2 -k4nr file
1 Like

Yoda, this iteration is causing the 4th column to no longer sort descending numerically. Think I tried this one.

I get:

$ sort -k2 -k4nr myFile
xxxx apples xxxx 100
xxxx apples xxxx 90
xxxx oranges xxxx 70
xxxx oranges xxxx 80
xxxx pears xxxx 100
xxxx pears xxxx 90

is that what you're NOT after?

1 Like

I'm on Solaris,

sort -k2 -k4nr file

is giving this:

xxxx apples xxxx 90 
xxxx apples xxxx 100 
xxxx oranges xxxx 80 
xxxx oranges xxxx 70
xxxx pears xxxx 90 
xxxx pears xxxx 100

don't have Solaris atm, but try this:

sort -k2 -k4n,4r myFile
1 Like

Yes! It works, it is the other real life data I am not showing in my example. Thanks guys.

I seem to get the NUMERICAL REVERSE sort of k4 only if it is the first key to sort by. Both for
sort (GNU coreutils) 5.3.0-20040812-FreeBSD and sort (GNU coreutils) 8.25 (linux) ,

EDIT: Yes, vgersh99 has got it! -k2 will use field 2 till end-of-line as a key....

Try:

sort -k2,2r -k4rn file

Output:

xxxx pears xxxx 100
xxxx pears xxxx 90
xxxx oranges xxxx 80
xxxx oranges xxxx 70
xxxx apples xxxx 100
xxxx apples xxxx 90