Reputation: 25986
Can someone see why I get
awk: cmd. line:8: function mma(num) {
awk: cmd. line:8: ^ syntax error
awk: cmd. line:8: function mma(num) {
awk: cmd. line:8: ^ syntax error
from this script?
echo "0.24 0.21 0.22 1/1282 10953" | awk '{
min=""
max=""
avg=""
# find min, max, avg
function mma(num) {
if(min==""){min=max=$1};
if($1>max) {max=$1};
if($1<min) {min=$1};
total+=$1;
count+=1;
avg=total/count;
}
mma($1)
mma($2)
mma($3)
print avg, max, min
}'
Upvotes: 0
Views: 759
Reputation: 26471
Definitions of functions can appear anywhere between the rules of an awk program. From the POSIX standard :
The awk language also provides user-defined functions. Such functions can be defined as:
function name([parameter, ...]) { statements }
A function can be referred to anywhere in an awk program; in particular, its use can precede its definition. The scope of a function is global. <snip> Function definitions can appear anywhere in the program where a pattern-action pair is allowed.
This means a valid awk program looks like :
( pattern1 ) { action1 }
function name([parameter, ...]) { statements }
( pattern2 ) { action2 }
...
In your original code, you wrote the incorrect
( pattern ) { function name([paramter, ...]) { statements }
action }
So the corrected version of your awk
part would be:
awk 'function mma(num) {
if(min==""){min=max=$1};
if($1>max) {max=$1};
if($1<min) {min=$1};
total+=$1;
count+=1;
avg=total/count;
}
{ min=""; max=""; avg=""
mma($1); mma($2); mma($3)
print avg, max, min
}'
update: from the comments, it might be more useful to use
awk '{ avg=($1+$2+$3)/3; min=avg; max=avg;
min=($1<min) ? $1 : min; max=($1>max) ? $1 : max
min=($2<min) ? $2 : min; max=($2>max) ? $2 : max
min=($3<min) ? $3 : min; max=($3>max) ? $3 : max
print avg,max, min } ' /proc/loadavg
However, this is questionable as taking the average of averages is very ...
Also interesting might be the sar
command.
Upvotes: 5