2

I am trying to write an awk script in ubuntu as a non-admin user. It takes four terminal statements and throws them into variables. Those variables then are sent to a function I made and it spits out an average number and prints it.

Here is my script:

#!/usr/bin/gawk -f
BEGIN{
one = ARGV[1];
two = ARGV[2];
three = ARGV[3];
four = ARGV[4];

function average_funct(one, two, three, four) 
{
total = one + two;
total = total + three;
total = total + four;
average = total / 4;
return average;
}

print("The average of these numbers is " average_funct(one, two, three, four));
}

To run it I have been using this:

./myaverage4 2 7 4 3

Which results in this error message:

gawk: ./myaverage4:9: function average_funct(one, two, three, four)
gawk: ./myaverage4:9: ^ syntax error
gawk: ./myaverage4:15:    return average;
gawk: ./myaverage4:15:    ^ `return' used outside function context

If anyone could help me figure out the problem that would be awesome.

Josiah
  • 37
  • 7

1 Answers1

3

You can't declare a function inside the BEGIN section or any other action block. Move it outside of all action blocks.

function foo() { ... }
BEGIN { foo() }

I assume you have some reason for writing your code the way you did rather than the more obvious and adaptable to any number of arguments:

function average_funct(arr,    total, cnt) 
{
  for (cnt=1; cnt in arr; cnt++) {
    total += arr[cnt]
  }
  return (--cnt ? total / cnt : 0)
}
BEGIN {
  print "The average of these numbers is", average_funct(ARGV)
}
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    I only required 4 arguments for this particular program but I like your version more. Also, I haven't come upon your answer for the last few hours of google and stackoverflow searches. Worked right after I moved the function! Thank you very much. – Josiah Mar 26 '17 at 03:50
  • 1
    I'll have to look into it. Thanks again Ed. – Josiah Mar 26 '17 at 03:55