res[0]="b 9" res[1]="a 1" res[2]="c 10" printf -- '%s\n' "${res[@]}"
I want to sort it and display the array by the order of the number in bash.
a 1 b 9 c 10
is this possible?
res[0]="b 9" res[1]="a 1" res[2]="c 10" printf -- '%s\n' "${res[@]}"
I want to sort it and display the array by the order of the number in bash.
a 1 b 9 c 10
is this possible?
Sort with sort
:
res[0]="b 9"
res[1]="x 1"
res[2]="c 10"
printf -- '%s\n' "${res[@]}" | sort -k2 -n
Output:
x 1 b 9 c 10
sort
:
res[0]="b 9"
res[1]="x 1"
res[2]="c 10"
new=() # declare array new
# copy array res to new and use second column as index
for ((i=0;i<${#res[@]};i++)); do
new[${res[$i]#* }]=${res[$i]% *}
done
# print array new and use its index: ${!new[@]}
for i in "${!new[@]}"; do
echo "${new[$i]} $i"
done
Output:
x 1 b 9 c 10