Thursday 15 August 2013

Linux shell scripting - Simple awk script issue -



Linux shell scripting - Simple awk script issue -

i'm trying simple awk script exercise , cannot figure why isn't working.

the awk script should used display entries begining 2012, given next 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 follows:

% awk -f awkscriptfile inputfile info year 2012 ================== jan : 321.11 feb : 1.99 feb : 32.99 mar : 11.45 =================== volume 2012 is: 367.54 4 records processed %

however, this:

% awk -f awkscriptfile inputfile info 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 2012 is: $sum $count records processed %

so awk script printing out lot more should, , reason sum , count variables aren't beingness printed.

this code awk script:

begin { print "data year 2012" print "==================================" count = 0 sum = 0 } $1 ~ /2012/ { print $2, " : ", $4 count++ sum += $4 } end { print "==================================" print "volume 2012 is: $sum" print "$count records processed" }

from i'm looking @ reference, see no reason why code shouldn't work. else can tell me i'm doing wrong.

awk -v y="2012" '$1==y{a[nr]=$2":"$4;s+=$4;c++} end{line="==================="; printf "data year %s\n%s\n",y,line; for(i=1;i<=nr;i++)if(a[i])print a[i] printf "%s\nvolume %s is: %.2f\n%d records processed\n", line, y, s, c}' file

with data, outputs:

data year 2012 =================== jan:321.11 feb:1.99 feb:32.99 mar:11.45 =================== volume 2012 is: 367.54 4 records processed

linux shell awk

No comments:

Post a Comment