Division by zero attempted error during linear conversion of values between 0.25 to 1

I want to implement the below formula with awk oneliner

new_value = ((old_value - old_min) / (old_max - old_min) ) * (new_max - new_min) + new_min

I want to pass the value of old_min and old_min as variable. Here is what I did for this

old_min=$(awk 'BEGIN{a=100000000000}{if ($10<0+a) a=$10} END{print a}' temp11)
old_max=$(awk 'BEGIN{a=   0}{if ($10>0+a) a=$10} END{print a}' temp11)
echo $old_min
4828
echo $old_max
449064

Then I run the command, which gives the error message

awk '{ print $0, (($10 - $old_min)/($old_max - $old_min)) * ((1 - 0.25) + 0.25)}' temp11
awk: cmd. line:1: (FILENAME=temp11 FNR=1) fatal: division by zero attempted

Then I tried simply which worked fine

awk '{ print $0, (($10 - 4828)/(449064 - 4828)) * (1 - 0.25) + 0.25}' temp11

but I need to assign $old_min and $old_max dynamically as my script.sh run it inside the loop. Thanks

shell variables are NOT available in awk . You need to use the -v option:

awk -vOLDMIN="$old_min" '{print OLDMIN}'

On top of vars not being available, with your syntax above you reference a field in awk , here $0 (the entire line) as old_min is undefined thus empty thus 0.

1 Like

Thanks the Error is gone. Here is what I did:

awk -v old_min=$old_min -v old_max=$old_max '{ print $0, (($10 - old_min)/(old_max - old_min)) * ((1 - 0.25) + 0.25)}' temp11
1 Like