#!/bin/sh

# Calculate avareage of columns - Fred 12 2021

cd /p/projects/best/fred/Bolivia/swim_bermejo_vs7/output/Res
ls wam_WU* > wamList

#echo
echo "Subbasin     PlantDemand_mm     PlantDemand_m3s     IrrDemand_m3s      Supplied_m3s     tr_Losses_m3s"

for i in `cat wamList`
do
  echo -n "$i     "
  sed 's/,/ /g' $i > wamQ       #replace comma
  
  awk '{NR>1}                   #skip first line
     {for(i=3; i<=NF; i++){     #for each column, starting with the 3rd
        sum[i] += $i;           #add the sum to the "sum" array
        if($i != "na"){         #if value is not "na"
           count[i]+=1}         #increment the column "count"
        }                       #endif
     }                          #endfor
    END {                       #at the end
     for(i=3; i<=NF; i++){      #for each column
        if(count[i]!=0){        #if the column count is not 0
            v = sum[i]/count[i] #then calculate the column mean (here represented with "v")
        }else{                  #else (if column count is 0)
            v = 0               #then let mean be 0 (note: you can set this to be "na")
        };                      #endif col count is not 0
        if(i<NF){               #if the column is before the last column
            printf "%f\t",v     #print mean + TAB
        }else{                  #else (if it is the last column)
            print v}            #print mean + NEWLINE
        };                      #endif
     }' wamQ                    #endfor (note: input.txt is the input file)
done
rm wamQ
#echo