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?

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

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.