Tursko
Tursko

Reputation: 132

How can I compare floats in bash

Working on a script and I am currently stuck. (Still pretty new at this)

First off I have my data file, the file I am searching inside. First field is name, second is money payed, and third is money owed.

customerData.txt

 name1,500.00,1000
 name2,2000,100
 name3,100,100.00

Here is my bash file. Basically if the owe amount is greater than the paid amount, then print the name. Works fine for anything thats not a float. I also understand that bash doesn't handle floats and the only way to handle them is with the bc utility, but I have had no luck.

#!/bin/bash

while IFS="," read name paid owe; do
    #due=$(echo "$owe - $paid" |bc -1)
    #echo $due
    if [ $owe -gt $paid ]; then
        echo $name
    fi
done < customerData.txt

Upvotes: 3

Views: 87

Answers (1)

John1024
John1024

Reputation: 113924

To print all lines for which the third column is larger than the second:

$ awk -F, '$3>$2' customerData.txt 
name1,500.00,1000

How it works

  • -F, tells awk that the columns are comma-separated.

  • $3>$2 tells awk to print any line for which the third column is larger than the second.

    In more detail, $3>$2 is a condition: it evaluates to true or false. If it evaluates to true, then the action is performed. Since we didn't specify any action, awk performs the default action which is to print the line.

Upvotes: 3

Related Questions