Paul
Paul

Reputation: 321

awk with zero output

I have four column and I would like to do this: INUPUT=

429 0   10  0
287 115 89  64
0   629 0   10
542 0   7   0
15  853 0   12
208 587 5   4
435 203 12  0
604 411 27  3
0   232 0   227
471 395 5   5
802 706 15  15
1288    1135    11  23
1063    386 13  2
603 678 7   14
0   760 0   11

awk '{if (($2+$4)/($1+$3)<0.2 || ($1+$3)==0) print $0; else if (($1+$3)/($2+$4)<0.2 || ($2+$4)==0) print $0; else print $0}' INPUT

But I have error message :

awk: cmd. line:1: (FILENAME=- FNR=3) fatal: division by zero attempted

Even if I have added condition:

...|| ($1+$3)==0...

Can somebody explain me what I am doing wrong?

Thank you so much.

PS: print $0 is just for illustration.

Upvotes: 0

Views: 69

Answers (2)

Azukikuru
Azukikuru

Reputation: 11

You're already dividing by zero in your conditional statement ($1+$3=0 on the ninth line of your list). That's where the error comes from. You should change the ordering in your conditional statement: first verify that $1+$3!=0 and only then use it to define your next condition.

Upvotes: 0

Jon Combe
Jon Combe

Reputation: 1806

Move the "($1+$3) == 0" to be the first clause of the if statement. Awk will evalulate them in turn. Hence it still attempts the first clause of the if statement first, triggering the divide by zero attempt. If the first clause is true, it won't even attempt to evaulate the second one. So:-

awk '{if (($1+$3)==0 || ($2+$4)/($1+$3)<0.2) print $0; else if (($1+$3)/($2+$4)<0.2 || ($2+$4)==0) print $0; else print $0}' INPUT

Upvotes: 2

Related Questions