Shell – Converting csv file (generated by db query) to html and color code the table based on Column Value

awkscriptingshell

(Using Shell Script) Need to generate html report from a CSV file which is an output of a DB query and then color code it based on column values. For example, from the given CSV ile, if any cell under column "status%" is less than 80, it should be highlighted ith red background, Anything >=90 Green.. I Tried using awk, but i was messing up with for loop.

CSV file is something like

Status%,Status Message,date 0f examination,type of exam,subject
75, success, 13-09-2013,mid term,physics
90, success, 15-09-203, mid term, Maths
100, success, 17-09-2013, term, biology
100, success, 17-09-2013, term, SST

Adding The Code

awk '
BEGIN {     
print "<html><body></br></br>The report provides overall Percentage Secured in the given subjects.</br></br></br>"
print "<table border=1 cellspacing=1 cellpadding=1>"
        } 
{
print "<tr>"
for ( i = 1; i <= NF; i++ )
{                                                    
if ($i <=75 )
  print "<td> <b><FONT COLOR=RED FACE="verdana"SIZE=2 ></b>"  $i  "</td>"
else
  if ($i >=90 && $i =100)
print "<td> <b><FONT COLOR=GREEN FACE="verdana"SIZE=2 ></b>"  $i  "</td>"
 else
print "<td> <FONT COLOR=YELLOW  FACE="verdana"SIZE=2 >" $i "</td>"
print "</tr>"
}
END { print "</table></body></html>"
}

'  /Reports/output/Output.html | sendmail -t

Best Answer

You have a good start but but are making some basic HTML errors, like never closing the <FONT> tag. Using this for your awk script should get you close to what you are looking for:

BEGIN {
  print "<html><body></br></br>The report provides overall Percentage Secured in the given subjects.</br></br></br>"
  print "<table border=1 cellspacing=1 cellpadding=1>"
}

NR==1 {
  # Header row
  print "<tr>"

  for ( i = 1; i <= NF; i++ ) {
    print "<td><b>"$i"</b></td>"
  }
  print "</tr>"
}

NR>1 {
  # Data rows
  print "<tr>"
  color="RED"
  if( $i > 80 ) {
    color="YELLOW"
  }
  if( $i > 90 ) {
    color="GREEN"
  }
  print "<td><b><FONT COLOR=\""color"\" FACE=\"verdana\" SIZE=2>"$1"</b></FONT></td><td>"$2"</td><td>"$3"</td><td>"$4"</td><td>"$5"</td>"
  print "</tr>"
}
END {
  print "</table></body></html>"
}

You can either run it inline as you are, or put this into its own file (e. g. reportgen.awk, and then run it with awk -f reportgen.awk /path/to/inputfile > outputfile.html.

Related Question