0

I have an array of strings:

arr[0]="1 10 2Z6UVU6h"
arr[1]="1 12 7YzF5mFs"
arr[2]="2 36 qRwAiLg7"

How could i sort by the 2nd column and use the 1st as a tie break.

Is there anything similar to something like...

sort -k 2,2n -k 1,1 $arr
Pablo
  • 3
  • 1
  • Here are some examples: [http://stackoverflow.com/questions/7442417/how-to-sort-an-array-in-bash.](http://stackoverflow.com/questions/7442417/how-to-sort-an-array-in-bash) instead of just `sort` use `sort -k2 -k1`. – James Brown Apr 25 '17 at 04:03

1 Answers1

1

As long as there are no newline characters in any array element, it's straight-forward: Just printf the array into sort and capture the output:

mapfile -t sorted < <(printf "%s\n" "${arr[@]}" | sort -k2,2n -k1,1)

(The use of process substitution is to avoid having the mapfile run in a subshell, which wouldn't be helpful since the goal is to set the value of $sorted in this shell.)

If the array elements might contain newlines, then you could use NUL as a delimiter in the printf and the sort (option -z for sort), but you'd have to replace mapfile with an explicit loop because mapfile does not offer an option to change the line delimiter. read does (-d '' will cause read to use NUL as a line delimiter), but it only reads one line at a time.

rici
  • 234,347
  • 28
  • 237
  • 341