How to Use user-defined Functions in awk

User-Defined Functions

You can create user-defined functions in a awk script file using the func or function keywords. Placement in the file is not important; the function definition can occur anywhere in the awk script.

The function can take arguments (local to the function only) or use any existing variable.

The syntax of a function definition is:

func function_name ([optional_arg] . . .) { statements } 

or

function function_name ([optional_arg] . . .) { statements }

The function_name is how the function is called at some other point in the program. Arguments are allowed but not required. In the definition of the function, only the names of the arguments are required. These arguments can be accessed only within the body of the function (the statements inside the curly braces). You might, however, access any other variable that is being used in the awk script from within a function.

For example:

$ cat func.awk 
func MAX(val1, val2) { 
        if (val1 > val2)
         return val1 
        else 
         return val2
                  } 
BEGIN {largest = 0}
{largest = MAX(largest, $5)} 
END {print largest}
$ awk -f func.awk data.file 
5.7

You can use the return statement to return a value from the function. Use this returned value to assign a value to a variable or to perform a test of some sort with an if statement. To perform such a test, the function is called within the if statement. If the function returns a nonzero value, the if statement considers the test to be true; if the function returns a zero value, the if statement considers the test to be false, and the if statements are not executed; for example:

if (function_call()) { statements }
Related Post