Calculate Median in Multiple Rows

I have a file name numbers, simply contain bunch random numbers

1     2     3
7     5     9
2     2     9
5     4     5
7     2     6

I have to create a script that find the median for each row, and here is my code:

while read -a row
do
  for i in "${row[@]}"
  do

    length=`expr ${#row[@]} % 2`
    if [ $length -ne 0 ] ; then
      mid=`expr ${#row[@]} / 2`
      echo ${row[middle]}
    elif [ $length -eq 0 ] ; then
      val1=`expr ${#row[@]} / 2`
      val2=`expr (${$row[@]} / 2) + 1`
      mid=`expr ($val1 + $val2) / 2`
      echo $mid
  done | sort -n
done < numbers

However this doesn’t work, it shows error instead. What mistake did I do in this code? Also I still haven’t figure out where is the proper way to place the sort -n since it needs to be sorted first before calculate the median, right?


Source: bash

Leave a Reply