AWK User-Defined Functions
Category Programming Techniques
A program contains multiple functionalities, each of which can be encapsulated in a separate function.
Functions enhance code reusability.
The syntax for user-defined functions is:
function function_name(argument1, argument2, ...)
{
function body
}
Explanation:
function_name is the name of the user-defined function. The name should start with a letter and can be followed by a combination of numbers, letters, or underscores. Reserved keywords in AWK cannot be used as function names.
User-defined functions can accept multiple input parameters, separated by commas. Parameters are not mandatory; functions can be defined without any input parameters.
function body is the part of the function that contains the AWK program code.
The following example implements two simple functions that return the minimum and maximum of two numbers, respectively. These functions are called in the main function. The code for the file functions.awk
is as follows:
# Returns the minimum value
function find_min(num1, num2)
{
if (num1 < num2)
return num1
return num2
}
# Returns the maximum value
function find_max(num1, num2)
{
if (num1 > num2)
return num1
return num2
}
# Main function
function main(num1, num2)
{
# Find the minimum value
result = find_min(10, 20)
print "Minimum =", result
# Find the maximum value
result = find_max(10, 20)
print "Maximum =", result
}
# Script execution starts here
BEGIN {
main(10, 20)
}
Executing the functions.awk
file yields the following results:
$ awk -f functions.awk
Minimum = 10
Maximum = 20
** Click to Share Notes
-
-
-