PDA

View Full Version : awk goodness



smokey
04-08-2005, 05:02 AM
Here's a quick snippet that I use all the time in awk:


BEGIN {print "string" + 5}

The nifty thing about this is that awk treats strings as the numerical value 0. This allows for some neat text-processing stuff, e.g.:


#!/usr/bin/awk -f
BEGIN {FS="\t"} # Set tab as Field Seperator
{TOT+=$2}
END {print "Total: " TOT}


This code will run through a tab-delimited flat file and add up all the numbers. I use this to balance my checkbook (among other things). If you have a file like this:


DATE AMT NOTE
---- --- ----
030105 -50 Pants
030505 20 Gift

The code above will correctly spit out '-30'. This is _much_ easier than achieving the same result in perl, where you'd have to account for the first two lines' string values in the second field. :toast:

sjohnson
04-08-2005, 03:11 PM
awk is a great language for certain tasks.

I wrote a 2 pager in awk for my ex's boss. They went from 5-6 hours of manual sorting to 10 minutes in awk. Got a box of homemade cookies for that one :)

bh2k
04-08-2005, 06:27 PM
Perl seriously hates me. Not to mention regular expressions which also hate me to a very high degree.