-1

shell script to sort numbers including decimal numbers

I tried the following script and list with decimal number not working.

arr=(10 8 -20 100 1.2)

echo "Array in original order" echo ${arr[*]}

for ((i = 0; i<5; i++)) do

for((j = 0; j<5-i-1; j++)) 
do

    if [ ${arr[j]} -gt ${arr[$((j+1))]} ] 
    then
         
        temp=${arr[j]} 
        arr[$j]=${arr[$((j+1))]} 
        arr[$((j+1))]=$temp 
    fi
done
done
echo "Array in sorted order :" echo ${arr[*]}

OUTPUT:

Array in original order 10 8 -20 100 1.2 ./sort.sh: line 17: [: 1.2: integer expression expected Array in sorted order : -20 8 10 100 1.2

i want the list to be as follow:

-20 1.2 8 10 100

11
  • 1
    How is this different from your previous question? Commented Feb 5, 2021 at 8:13
  • please see this thread which has the answer: stackoverflow.com/questions/9939546/… Commented Feb 5, 2021 at 8:18
  • 1
    Is this a homework question to implement a sorting algorithm, or are external binaries allowed (such as sort) Commented Feb 5, 2021 at 11:39
  • 1
    @kvantour : Maybe we have some misunderstanding here, but for all that I know, POSIX shell neither has arrays nor floating point arithmetic. If you have different information, I would appreciate if you can provide me some link on that matter. Commented Feb 6, 2021 at 17:32
  • 1
    @user1934428 ZSH does have knowledge of sorting. Have a look at the glob-qualifiers o and O to sort arrays. Commented Feb 8, 2021 at 8:24

1 Answer 1

1

i want the list to be as follow: -20 1.2 8 10 100

  1. Output numbers one per line.
  2. Sort
  3. Join with space

$ arr=(10 8 -20 100 1.2)
$ printf "%s\n" "${arr[@]}" | sort -g | paste -sd' '
-20 1.2 8 10 100

Don't reimplement sort using shell - it's going to be incredibly slow. The -g option to sort may not be available everywhere - it's for sorting floating point numbers.

[: 1.2: integer expression expected Array

The [ command handles integers only. 1.2 has a comma, [ can't handle it. Use another tool. Preferable python.

${arr[$((j+1))]}

No need to use $(( - stuff inside [ is already expanded arithmetically. Just ${arr[j+1]}.

j<5-i-1

is strange condition. When i=4 then it's j<0 and loop will not run at all. Just iterate from i instead of up to i - ((j=i;j<5;++j)).

echo "Array in sorted order :" echo ${arr[*]}

Will print echo to output. Just echo "Array in sorted order : ${arr[*]}" or echo "Array in sorted order :" "${arr[@]}"

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.