Advertisement
homer512

balance computation

May 12th, 2014
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Awk 1.81 KB | None | 0 0
  1. #!/bin/awk -f
  2.  
  3. # see http://theunixshell.blogspot.de/2014/05/comparing-two-files-using-awk.html
  4.  
  5. BEGIN {
  6.     if(ARGC != 3) {
  7.     printf("Usage: %s company_file balance_file\n", ARGV[0])
  8.     exit 2
  9.     }
  10.     # split on dollar sign for easier processing of second file
  11.     FS = "$"
  12. }
  13.  
  14. # Sanitize and filter input first
  15. # We use the NR == FNR idiom to distinguish the two files
  16. # We are also very forgiving when it comes to company names. They just have
  17. # to start with a non-whitespace and cannot contain dollar signs
  18. (NR == FNR && ! /^[^\s\$][^$]*$/) ||
  19. (NR != FNR &&
  20.  ! /^[^\s\$][^$]*\s+\$[[:digit:]]+\.[[:digit:]]{2}\s+((due)|(payment))$/) {
  21.     printf("Formatting error in file '%s', line %d: '%s'\n", FILENAME, FNR,
  22.        $0) > "/dev/stderr"
  23.     next
  24. }
  25.  
  26. # both files: Retrieve name of company by removing trailing whitespace
  27. {
  28.     company = gensub(/\s+$/, "", 1, $1)
  29. }
  30.  
  31. # company_file: Initializes balance array in case a company made no entries in
  32. # the balance file.
  33. # Aborts processing of this line at the end so that we don't have to check for
  34. # NR != FNR in the rest of the script
  35. NR == FNR {
  36.     balance[company] = 0.
  37.     next
  38. }
  39.  
  40. # balance_file: Retrieve amount of money.
  41. # Note that $2 contains everything up to the end of the file but strtonum will
  42. # abort without error on the first non-digit
  43. # We also check for companies not defined in company_file and skip them
  44. {
  45.     money = strtonum($2)
  46.     if(! company in balance) {
  47.     printf("Undefined company '%s' in file '%s', line '%d'\n", company,
  48.            FILENAME, FNR) > "/dev/stderr"
  49.     next
  50.     }
  51. }
  52.  
  53. # add or subtract money depending on instruction
  54. /due$/ {
  55.     balance[company] -= money
  56. }
  57.  
  58. /payment$/ {
  59.     balance[company] += money
  60. }
  61.  
  62. # print balance
  63. END {
  64.     for (company in balance)
  65.     printf("%s\t$%.2f\n", company, balance[company])
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement