garcesj
garcesj

Reputation: 589

Two field division, awk

I've get stuck with (maybe very easy) function in awk: I'm trying to divide two fields row by row with the following code:

awk 'BEGIN{FS=OFS="\t"} $43 > 0 && $31 > 0 {$43/$31; print}' file.tsv

But I'm getting continuously this error: fatal: division by zero attempted, but I've already check that denominator is always distinct from zero (and indeed, I think the code should be discarding zeroes) and I've no idea what's happening... any suggestion, please? Thanks a lot!

EDIT: The input table has this format (awk 'BEGIN{FS=OFS="\t"} {print $31,$43}' file.tsv | head -4):

triCount_PM triSum_altPM
3   25
3   7
3   0

Upvotes: 0

Views: 285

Answers (2)

tripleee
tripleee

Reputation: 189387

E.g. "fnord" > 0 evaluates to true in Awk; you really need to make sure the values are properly numeric. A common trick for coercing a number interpretation is to add zero.

awk 'BEGIN{FS=OFS="\t"} 0+$43 > 0 && 0+$31 > 0 { print $43/$31 }' file.tsv

Just print always prints $0 (which is initialized to the current input line, though you can change it directly or indirectly from your program); to print something else, pass that "something else" as an argument to print.

Upvotes: 2

karakfa
karakfa

Reputation: 67497

The division-by-zero results from the header which does not have numbers for the fields so both fields are zero. To make this work, you need to skip the header (NR == 1 tests for the first line)

$ awk 'NR==1{print "$43/$31"; next} $43>0 && $31>0 {print $43/$31}' file

Upvotes: 1

Related Questions