command line - Errors in Averaging Function Script Code? - Ask Ubuntu
i wrote (questionable) piece of code user-defined average function, code takes second argument of command line invocation, , uses respective field in input file , finds average of of fields (in single column).
the input file named players.data
:
lbj:1:1:1:1 kbb:2:2:2:2 kdd:3:3:3:3 ppp:4:4:4:4 llo:5:5:5:5
my function supposed to, depending on second argument @ invocation, find average of 5 numbers in either 3rd, 4th or fifth column (field).
so given invocation nawk -f testscript2.script players.data row3
should use row3 argv[2]
, , according below if statement sum row 3 in players.data
, output the average of row row3 5.00
error-ridden code listed below:
begin{fs = ":"} { function average(argv[2]){ if(argv[2] == "row3"){ sumjan += $3 avgjan = sumjan / 5 printf "the average of row %-10s %6.2f", argv[2], avgjan } else if(argv[2] == "row4"){ sumfeb += $4; avgfeb = sumfeb / 5 printf "the average of row %-10s %6.2f", argv[2], avgfeb } else if(argv[2] == "row5"){ summar += $5 avgmar = summar / 5 printf "the average of row %-10s %6.2f", argv[2], avgmar } else{ print "error: invalid input" } } } {average(argv[2]) }
here summary of current errors:
nawk: a6c.script: line 8: syntax error @ or near function nawk: a6c.script: line 15: syntax error @ or near else nawk: a6c.script: line 20: syntax error @ or near else nawk: a6c.script: line 25: syntax error @ or near else nawk: a6c.script: line 28: syntax error @ or near }
how code fixed such when above invocation passed desired output displayed?
first, grammar errors
you have 1 {
before line function
:
begin{fs = ":"} { function average(argv[2]){ ... }
so should be:
begin{fs = ":"} function average(argv[2]){ ... }
then, creating function receives parameter. parameter supposed have local scope of function, hence calling argv[2]
big misunderstanding of scopes. use like:
function average(row) { # things variable row }
and use argv[2]
when calling function: average(argv[2])
.
then, concept errors
you using function call on every iteration calculate average. if want use functions, use 1 keep track of values , finally, , then, print values.
also, repeating bunch of code in if - else if - else
conditions. note as can $4
, can var=row
, use $var
use row
th's value:
if(argv[2] == "row3"){ sumjan += $3 avgjan = sumjan / 5 printf "the average of row %-10s %6.2f", argv[2], avgjan }
can generic:
sum += $row avg = sum / 5 printf "the average of row %-10s %6.2f", row, avgjan
altogether, can succinct one-liner
$ awk -f: -v col=4 '{sum+=$col} end {print sum/nr}' file 3
this keeps sum of column number col
, divides number of lines.
Comments
Post a Comment