Zocr
Zocr

Reputation: 103

Bash - sorting by substring of elements

I would like to sort the elements in a list by the second and third char of the elements in reverse , i.e sort by the 3rd char first and then 2nd char.

eg. If there's an array like this

array=(XA11000 XB21000 XA31000 XB12000)

The desired output of the sort would be (XA31000 XB21000 XB12000 XA11000)

It's relatively simple without the 4 digits at the end of each elements as

echo "${array[@]}"|rev | sort -r | rev

would work.

However I'm not too sure how this would work with the numbers at the end. Any suggestions?

Upvotes: 5

Views: 7845

Answers (1)

choroba
choroba

Reputation: 241828

sort has the option -k where you can specify how to sort:

(   IFS=$'\n'
    echo "${array[*]}" | sort -k1.3,1.3r -k1.2,1.2r
)

i.e. sort by the substring from the first word third character (-k1.3) to first word third character (,1.3) reversed r, secondary sorting by the first word second character.

Upvotes: 12

Related Questions