Search code examples
shellawkfatal-errordivisiondivide-by-zero

Dealing with variable inside awk result division by zero


I'm writing a simple shell command using awk, as follow:

input_folder='/home/Desktop/files'
results_folder='/home/results'

for entry in $input_folder/*
do

re=$(samtools view -H $entry | grep -P '^@SQ' | cut -f 3 -d ':' | awk '{sum+=$1} END {print sum}')

echo -e "$(samtools depth $entry | awk '{sum+=$3} END { print $(sum/$re)}')\t/$entry" >> $results_folder/Results.txt

done

the result in variable re is a number but using the result of re into the second command print $(sum/$re)}' give me this error awk: cmd. line:1: (FILENAME=- FNR=312843568) fatal: division by zero attempted

I tried not to put $ with the variable but also the same error.

Any help with that please?


Solution

  • Change the awk part to:

    awk -v re="$re" '{sum+=$3} END { if(re) print sum/re; else print "oo";}'
    

    You have to use -v to transfer the variable into awk.
    And also it's better to check if re is zero.
    I used oo to represent Infinity symbol.