0

I want to sort an array of numbers and put into another array. The following code is what I found

IFS=$'\n' sorted=($(sort <<<"${array[*]}"))
unset IFS
echo "${sorted[*]}"

However, this does so by string

1 12 5 111 200 1000 10
1 10 1000 111 12 200 5

How do I get it sorted by number?

1
  • 1
    Just Use sort -n Commented Feb 13, 2018 at 15:42

2 Answers 2

2

This code uses \0 as delimiter and is therefore suitable even for sorting non-numerical arrays:

arr=(4 2 3 1 5)
sorted=()

while IFS= read -r -d '' item; do
    sorted+=("$item")
done < <(printf '%s\0' "${arr[@]}" | sort -zn)

In bash 4.4 you can also utilize readarray:

readarray -d '' sorted < <(printf '%s\0' "${arr[@]}" | sort -zn)
Sign up to request clarification or add additional context in comments.

Comments

1

Without modifying IFS.

$ p=(1 10 1000 111 12 200 5)
$ sorted_p=($(tr ' ' '\n' <<<"${p[@]}" | sort -n))
$ echo "${sorted_p[@]}"
1 5 10 12 111 200 1000

2 Comments

The second tr is not really necessary :)
That's right. I pasted from a test I was doing with echo at that moment. Edited...

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.