Sunday, November 05, 2006

Better Script

On 1 Nov 2006, Linux Journal Weekly Newsletter posted the following script.
 THE BRAIN TRUST: READERS SHARE THEIR EXPERTISE

   Thanks to Josmar in (I'm totally jealous) Paraná, Brazil for this tip:

   Writing a CGI module entirely in BASH is a lot of fun. When, however, you
   have to find something in a certain file and render just some of the fields
   in an HTML table, this little trick always helps.

   Lets say you have something like this expense report in a file named
   "expenses.txt":

      John, lunch, 3.50, Apr/01/2006
      Karen, dinner, 8.00, May/30/2006
      John, parking, 1.00, May/30/2006
      Peter, dinner, 4.00, Apr/02/2006
      Karen, lunch, 6.00, May/30/2006

   And you need to render a HTML table for Karen's expenses, like this one:

         Date      Cost  Description
      May/30/2006  8.00    dinner
      May/30/2006  6.00    lunch

      Total Karen's expenses: 14.00

   This script converts the "expenses.txt' file into the HTML you need to
   produce the table above.

      #!/bin/bash
      PERSON="Karen"
      grep -iF "$PERSON" expenses.txt | cut -f 2-4 -d , | tr -d ',' > /tmp/exp1.$$
      if [ -s /tmp/exp1.$$ ]; then
         TOTAL=0
         echo "<table border=\"1\"><tr><th>Date</th><th>Cost</th><th>Description</th></tr>"
         for I in `cat /tmp/exp1.$$ | tr ' ' '_' `; do
         echo "$I" | tr '_' ' ' > /tmp/exp2.$$
         read DESCR COST DATE < /tmp/exp2.$$
         echo "<tr><td>$DATE</td><td>$COST</td><td>$DESCR</td></tr>"
         TOTAL=`echo "$TOTAL+$COST" | bc`
         done
         echo "</table><p>Total $PERSON's expenses: $TOTAL</p>"
      else
         echo "No data for '$PERSON'"
      fi
      rm /tmp/exp1.$$ /tmp/exp2.$$

   You can also use this script as a basic template for creating scipts to
   convert CSV (comma separated values) files into HTML tables. Most databases
   and spreadsheets can export data directly into CSV files.

   Thanks to everyone for your tips! Please send more of them to share with our
   community of readers! My email is jgray@ssc.com. We'll send you a free
   t-shirt for your efforts (or a penguin chair for the best one)! Thanks!
I think there is a better solution to the problem. Below script was posted back to the editor. As you can see, it needs far less UNIX commands and there is no need to create temporary files.
#! /bin/sh

if [ $# -ne 1 ]; then
        echo "Usage: $0 <name>"
        exit 1
fi

awk -F"," '
BEGIN {
        print "<table>"
        print "<tr><td>Date</td><td>Cost</td><td>Description</td></tr>"
}
$1 == "'$1'" {
        printf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>\n",$4,$3,$2)
}
END {
        print "</table>"
}' expense.txt 

Labels: , ,

0 Comments:

Post a Comment

<< Home