3

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
Tursko
  • 132
  • 1
  • 9

1 Answers1

3

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.

John1024
  • 109,961
  • 14
  • 137
  • 171
  • I was using awk, but this is actually for a bigger project in which I use data from this file to fill in things on an email template. I guess I could use awk and print all the whole line onto a temp file, then access that file using the while (which will have all the correct values). – Tursko Mar 07 '18 at 06:39
  • @Tursko I don' know the details of what "fill in things on an email template" involves but, because awk supports `printf`, it is capable of printing complex output. It can also process multiple files, say, gathering email addresses from one, selecting debtors from another and writing output to a third file. – John1024 Mar 07 '18 at 06:41
  • I use sed to replace things like to the name I grab from the file. Your solution does help me though. – Tursko Mar 07 '18 at 06:42
  • Because awk has builtin substitution functions (like `sub` and `gsub`), it can do most anything that sed can do. – John1024 Mar 07 '18 at 06:44
  • I am going to mark your answer as the solution since it does work for the question that I asked. Thank you, I didn't even think of doing this. – Tursko Mar 07 '18 at 06:44