I have a tab delimited file that looks something like this:
foo 0 4
boo 3 2
blah 4 0
flah 1 1
I am trying to calculate log2 for between the two columns for each row. my problem is with the division by zero
What I have tried is this:
cat file.txt | awk -v OFS='\t' '{print $1, log($3/$2)log(2)}'
when there is a zero as the denominator, the awk will crash. What I would want to do is some sort of conditional statement that would print an “inf” as the result when the denominator is equal to 0.
I am really not sure how to go about this?
Any help would be appreciated
Thanks
You can implement that as follows (with a few additional tweaks):
Explanation:
if ($2==0) {print $1, "inf"} else {...}– First check to see if the 2nd field ($2) is zero. If so, print$1andinfand move on to the next line; otherwise proceed as usual.BEGIN{OFS="\t"}– SetOFSinside the awk script; mostly a preference thing.... file.txt– awk can read from files when you specify it as an argument; this saves the use of a cat process. (See UUCA)