Thursday, May 26, 2022

[SOLVED] min and max of float array bash

Issue

I have an array of floats in bash: eg:

array(1.0002, 1.00232, 1.3222, ....)

I want to find the maximum and the minimum element of the array using bash. The problem with this is that I have float elements that are not quite supported in bash.

I have tried for example:

IFS=$'\n'
echo "${ar[*]}" | sort -nr | head -n1

but it does not work for floats.

What is the best way to do this ?


Solution

There are probably many ways and I don't claim the two following are "the best".

You could use a calculator that supports floats, like bc, for instance:

max="${array[0]}"
min="${array[0]}"
for v in "${a[@]}"; do
  max=$(echo "if($v>$max) $v else $max" | bc)
  min=$(echo "if($v<$min) $v else $min" | bc)
done
echo "max=$max"
echo "min=$min"

awk also supports floats, so the following would do the same:

printf '%s\n' "${array[@]}" | \
awk '$1>max||NR==1 {max=$1}
     $1<min||NR==1 {min=$1}
     END {print "max=" max; print "min=" min}'


Answered By - Renaud Pacalet
Answer Checked By - David Goodson (WPSolving Volunteer)