Madza Farias-Virgens
Madza Farias-Virgens

Reputation: 1061

awk if 0 divided by x output 0

I have file

chr     gene    start   end     totsites        synWBM  synBF   misWBM  misBF
NC_044998.1     LOC100221041    14582   80739   14237   99      98      284     285
NC_044998.1     DCBLD2  31388   68748   10471   145     149     503     499
NC_044998.1     CMSS1   80874   299341  11061   48      48      179     178
NC_044998.1     FILIP1L 112495  297570  49095   170     173     642     639
NC_044998.1     LOC116808959    287349  289742  3010    0       0       0       0
NC_044998.1     TBC1D23 300404  343805  7190    39      39      153     154
NC_044998.1     NIT2    333622  344667  2828    18      18      63      63
NC_044998.1     TOMM70  346168  368957  4041    27      27      95      95
NC_044998.1     LNP1    371654  380427  2264    27      30      93      90

I'm trying to have $10 be $6/$5 using

awk '$$10 = $6/$5' file

but awk wont output the lines for which $6 = 0

I would like to have instances where $6 = 0 as 0

Upvotes: 1

Views: 128

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133508

Could you please try following, In case your Input_file is NOT having 5th field in any line then adding 1 condition here to avoid error of fatal: division by zero attempted lets add additional check to avoid this error.

awk 'FNR>1 { print $0"\t"($5?$6/$5:"NaN") }' Input_file

Upvotes: 4

David C. Rankin
David C. Rankin

Reputation: 84561

You can do it quite easily by appending $6/$5 to the end of the record. For example:

awk 'FNR>1 { print $0"\t"$6/$5 }' file

(FNR>1 will skip the first row, you can output it with a rule FNR==1 {print $0}, or just FNR==1 {print} , if you like)

Example Output

With your data in file, the above would produce:

NC_044998.1     LOC100221041    14582   80739   14237   99      98      284     285     0.00695371
NC_044998.1     DCBLD2  31388   68748   10471   145     149     503     499     0.0138478
NC_044998.1     CMSS1   80874   299341  11061   48      48      179     178     0.00433957
NC_044998.1     FILIP1L 112495  297570  49095   170     173     642     639     0.00346267
NC_044998.1     LOC116808959    287349  289742  3010    0       0       0       0       0
NC_044998.1     TBC1D23 300404  343805  7190    39      39      153     154     0.0054242
NC_044998.1     NIT2    333622  344667  2828    18      18      63      63      0.00636492
NC_044998.1     TOMM70  346168  368957  4041    27      27      95      95      0.00668151
NC_044998.1     LNP1    371654  380427  2264    27      30      93      90      0.0119258

Let me know if you have further questions.

Upvotes: 4

Related Questions