5

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?

2
  • I may just be slow, but it is entirely unclear the sort order you want? sort ... by the second and third char of the elements in reverse , i.e sort by the 3rd char first and then 2nd char. Does this mean the second and third char after reverse ignoring leading 000? ...and.. your explanation of ` 3rd char first and then 2nd char` would apply without reversing? Commented Sep 7, 2015 at 20:43
  • sorry should've been more clear. What I meant was I would like to pipe the result of sorting the 3rd character in descending order first, then pipe the result and sort by the second character in descending order. Commented Sep 7, 2015 at 22:15

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Dumb question, what do the parentheses do? Just curious. Nice answer +1
create a subshell, so the IFS change isn't propagated outside of it
@l'L'l: The whole thing runs in a subshell to localize the change in IFS (which separates the array members by newlines).
@choroba: Thanks — makes perfect sense now. (good hint BroSlow) :)
This site ss64.com/bash/sort.html provides examples of sorting with use of -k argument. I found it useful.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.