AWK - User Defined Functions

Functions are basic building blocks of a program. AWK allows us to define our own functions. A large program can be divided into functions and each function can be written/tested independently. It provides re-usability of code.
Given below is the general format of a user-defined function −

Syntax

function function_name(argument1, argument2, ...) { 
   function body
}
In this syntax, the function_name is the name of the user-defined function. Function name should begin with a letter and the rest of the characters can be any combination of numbers, alphabetic characters, or underscore. AWK's reserve words cannot be used as function names.
Functions can accept multiple arguments separated by comma. Arguments are not mandatory. You can also create a user-defined function without any argument.
function body consists of one or more AWK statements.
Let us write two functions that calculate the minimum and the maximum number and call these functions from another function called main. The functions.awk file contains −

Example

# Returns minimum number
function find_min(num1, num2){
   if (num1 < num2)
   return num1
   return num2
}
# Returns maximum number
function find_max(num1, num2){
   if (num1 > num2)
   return num1
   return num2
}
# Main function
function main(num1, num2){
   # Find minimum number
   result = find_min(10, 20)
   print "Minimum =", result
  
   # Find maximum number
   result = find_max(10, 20)
   print "Maximum =", result
}
# Script execution starts here
BEGIN {
   main(10, 20)
}
On executing this code, you get the following result −

Output

Minimum = 10
Maximum = 20

Contact

Talk to us

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores iusto fugit esse soluta quae debitis quibusdam harum voluptatem, maxime, aliquam sequi. Tempora ipsum magni unde velit corporis fuga, necessitatibus blanditiis.

Address:

৪৭/ দক্ষিণ বেগুনবাড়ি তেজগাঁও শিল্প এলাকা ঢাকা ১২০৮

Work Time:

সোমবার - শুক্রবার থেকে সকাল 9 টা থেকে বিকাল 5 টা

Phone:

+88 019 4145 2627