0
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?

user121196
  • 30,032
  • 57
  • 148
  • 198

1 Answers1

6

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


Numeric sort without 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
Cyrus
  • 84,225
  • 14
  • 89
  • 153