awk - Division with condition

Hi Friends,

I have an input file like this

cat input
chr1 100 200 1 2
chr1 120 130 na 1
chr1 140 160 1 na
chr1 170 180 na na
chr1 190 220 0 0
chr1 220 230 nd 1
chr2 330 400 1 nd
chr2 410 450 nd nd
chr3 500 700 1 1

I want to calculate the division of 4th and 5th columns. But, if either of the columns has

na or nd or 0

, I want my output to be nf.

So, my output would be

cat output
chr1 100 200 1 2 0.5
chr1 120 130 na 1 nf
chr1 140 160 1 na nf
chr1 170 180 na na nf
chr1 190 220 0 0 nf
chr1 220 230 nd 1 nf
chr2 330 400 1 nd nf
chr2 410 450 nd nd nf
chr3 500 700 1 1 1

I tried the division already, but it it throwing an error saying fatal error, division by zero attempted.

Thanks in advance.

Try:

awk '$4~"^na$|^nd$|^0$"||$5~"^na$|^nd$|^0$"{$6="nf";print;next}{$6=$4/$5}1' file
1 Like
awk '{print $0, ($4+0 && $5+0)? $4/$5 : "nf"}' file
1 Like

another lengthy way.. :smiley:

 
awk '{if($NF ~ /[1-9]/ && $(NF-1) ~ /[1-9]/){$(NF+1)=$(NF-1)/$NF}else{$(NF+1)="nf"}}1' file
1 Like