How to apply different sorting methods to different columns in a CSV file in BASH?

I have a CSV file like this:

awk -F',' '{print length($1),$0}' file.csv | sort -k1nr | cut -d' ' -f 2- will sort the file by word length, for all words appearing in the first column:

sort -t, -k+2 -n -r file.csv will sort the file from greatest to least according to the number appearing in the second column:

How can I use these two commands together such that the CSV file is first sorted by word length, according to the words appearing in the first column, then any rows containing words of equal length within the first column are sorted according to the number appearing in the second column from greatest to least. The resulting output would look like this:

How can these two sorting methods be used together?

If you are using then you can use the asort function to perform sort, so no other utility has to be called. You can try something like this:

Output:

This script reads all the lines first then it sorts the array called a with the function cmp. The only trick I used that a > b returns the usual 1 or 0 for true or false.

A little bit shorter version in :

This is not 100% correct as $F[1] contains the \n, yet printf handles it properly.