I'm trying to do a very simple awk script exercise and cannot figure why it isn't working.
The awk script should be used to only display entries begining with 2012, so given the following input file:
2009 Dec X 29.44
2009 Dec Y 32.32
2012 Jan X 321.11
2012 Feb Y 1.99
2012 Feb X 32.99
2012 Mar X 11.45
2010 Jan X 14.75
2011 Feb Y 21.00
2011 Mar X 7.77
The output should be as follows:
% awk -f awkscriptfile inputfile
Data for year 2012
==================
Jan : 321.11
Feb : 1.99
Feb : 32.99
Mar : 11.45
===================
volume for 2012 is: 367.54
4 records processed
%
However, what I get is this:
% awk -f awkscriptfile inputfile
Data for year 2012
==================================
2009 Dec X 29.44
2009 Dec Y 32.32
2012 Jan X 321.11
Jan : 321.11
2012 Feb Y 1.99
Feb : 1.99
2012 Feb X 32.99
Feb : 32.99
2012 Mar X 11.45
Mar : 11.45
2010 Jan X 14.75
2011 Feb Y 21.00
2011 Mar X 7.77
==================================
volume for 2012 is: $sum
$count records processed
%
So the awk script is obviously printing out a lot more than it should, and for some reason the sum and count variables aren't being printed.
This is my code for the awk script:
BEGIN {
print "Data for year 2012"
print "=================================="
count = 0
sum = 0
}
$1 ~ /2012/ {
print $2, " : ", $4
count++
sum += $4
}
END {
print "=================================="
print "volume for 2012 is: $sum"
print "$count records processed"
}
From everything I'm looking at for reference, I see no reason why this code shouldn't work. Hopefully someone else can tell me what I'm doing wrong.
{print}action.$on variables and they don't interpolate in strings. So those last two lines want to beprint "volume for 2012 is : "sumandprint count " records processed".#comments with C++-style//comments, and none is springing to mind..//does not work in bash either... possibly csh though I suppose. And yes,//is a regex that matches anything and as such will run a default action to print the line (though I'm surprised the rest of your comment didn't cause problems but I suppose awk just saw the words as blank variables or something.