LINUX AWK Tutorial Series | Chapter 12

In the previous chapter, we learned about Built-in functions, now in this post, I am going to share about user-defined functions in AWK.
This would be the last chapter in the AWK series. If I would get more things to share then will add them to the series.

User-Defined Function:

These functions are created by users for specific requirements.

Defining Syntax:

function <function_name>(arguments)
{
function body
}

Calling a function

<function name>(arguments)

No space has to be given between function name and parenthesis.

The function can also return a value using Return expression.

Syntax: return [expression]

The expression is optional for return.

Example 1:

Now if you gone through the previous chapter, We have employee data. I want to print the salary in words.

like 42000--> 42Thoudand
[himanshu@oel7 AWK]$ cat Employee_Data.csv
Bob,M,Human Resources,30000
Alice,F,Human Resources,45000
Mark,M,Human Resources,30000
Robin,M,Human Resources,20000
Maria,F,Human Resources,30000
Kevin,M,Human Resources,60000
Robert,M,Human Resources,42000

Now below is the example script which I have written. In this example, I have written if the argval(it is an argument to function) that is salary column $4 is 0 then it will print "zero" else it will use substr function to print the positions.
In this example, I have even used if else in awk.
[himanshu@oel7 AWK]$ cat user_function
function conver(argval) {
     if(argval ==0)
         printf("zero")
     else
     {
     	a[1]=substr(argval,1,2)
     	a[2]=substr(argval,3,1)
     	a[3]=substr(argval,4,1)
     	a[4]=substr(argval,5,1)
     	if(a[1]!=0)
	     printf(a[1] "Thousand ") 
     	if(a[2]!=0)
     	     printf(a[2] "Hundred")
     	if(a[3]!=0)
	     printf(a[3] " ")
     	if(a[4]!=0)
     	     printf(a[4] " ")
	}	
     printf("\n")
}

{printf $1 ": "; conver($4)}


When I execute the output will be like:



Example 2:

Now let's write a function to calculate the average of an array.

I have written a script as below with return.


[himanshu@oel7 AWK]$ cat return_average_func
function avg(arr)
{
     for (i in arr) {
               n++
               sum += arr[i]
     }
     ret=sum/n
     return ret
}

BEGIN{
     
     nums[1]=20
     nums[2]=-9
     nums[3]=10
     nums[4]=8
     nums[5]=-2
    
     print avg(nums)
}

arr--array name

[himanshu@oel7 AWK]$ awk -f return_average_func
5.4
Try to practise more with AWK and feel free to ask your doubts in comments sections.


If you like please follow and comment