Pablo
Pablo

Reputation: 3

Sort multiple column String array in bash

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

Upvotes: 0

Views: 640

Answers (1)

rici
rici

Reputation: 241701

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.

Upvotes: 1

Related Questions