Tuesday, May 23, 2006

Simple AWK scripts

For basic info on awk there's always the man page
Or try here for an indepth man page with examples

Here's some examples of my own:

To find the total all the values in column 2 of the CSV file:

awk 'BEGIN{FS=","; OFMT="%.2f"; total=0}{total+=$2}END{print total}' filename

I had an issue in the past when trying to do addition on very large numbers, so came up with this little function:

function sublong(value1,value2)
{
if ( length(value1) >= 7 ) {
remainder=value1%1000000
expo=int(value1/1000000)
output=expo""(remainder-value2)
} else {
output=value1-value2
}
return output

}

There might be a far better way to do this - answers on a postcard please...