awk command in script gives error while same awk command at prompt runs fine: Why?

Hello all,

Here is what my bash script does: sums number columns, saves the tot in new column, outputs if tot >= threshold val:

> cat getnon0file.sh
#!/bin/bash
this="getnon0file.sh"
USAGE=$this" [filename threshold_value]
InFile="xyz.38"
Min="0.05"
#[ I removed the input check to shorten the code]

awk '{sum=0; for(n=2; n<=NF; n++){sum+=$n}; tot=(NF+1);$tot=sum; if(sum>=0.05); {print}}' $InFile > $InFile.non0

echo ----  $this over ---  Result saved into $InFile.non0

When I call the script at the prompt, I get an error:

> getnon0file.sh xyz.38 0.05
/path/getnon0file.sh: line 36: syntax error near unexpected token `('
/path/getnon0file.sh: line 36: `awk '{sum=0; for(n=2; n<=NF; n++){sum+=$n}; tot=(NF+1);$tot=sum; if(sum>=0.05); {print}}' $InFile > 
$InFile.non0'

When I run the awk command alone at the prompt, I obtain the results I want

> awk '{sum=0; for(n=2; n<=NF; n++){sum+=$n}; tot=(NF+1);$tot=sum; if(sum>=0.05); {print}}' xyz.38 > xyz.38.non0

Is there any way around what seems to me an attractable error?

Thanks.

Just in case you need it, the datafile (xyz.38) look like this:

code1_001 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.008 0.028 0.198 0.502 0.625
code1_002 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.009 0.066 0.158 0.190
code1_003 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.009 0.060 0.148 0.185
code1_004 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 0.992 0.954 0.676 0.192 0.000
code2_001 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.008 0.055 0.229 0.390
code2_002 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.004 0.024 0.108 0.193
code2_003 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.029 0.118 0.209

The error could be anywhere. If it's not the missing quote here:

 
USAGE=$this"

... post/attach the entire script.

1 Like

Thanks for your good eyes, radoulov;
Bad quoting was the problem.

The awk command can be shorter.

awk '{sum=0; for(n=2; n<=NF; n++){sum+=$n};  if(sum>=0.05) print $0,sum}' $InFile

That's right!
Thanks!