Linux-AWK/C2/User-Defined-Functions-in-awk/English

From Script | Spoken-Tutorial
Jump to: navigation, search

Title of script: User Defined Function in Awk

Author: Antara Roy Choudhury

Keywords: Function definition syntax, Function call, Return statement, User defined function in awk


Visual Cue
Narration
Slide 1: Introduction Welcome to this Spoken Tutorial on User-defined function in awk.
Slide 2: Learning Objective In this tutorial we will learn about-
  • The syntax of function definition
  • Function call and
  • Return statement

We will do this through some examples.

Slide 3: System requirement To record this tutorial, I am using
  • Ubuntu Linux 16.04 OS and
  • gedit text editor 3.20.1

You can use any text editor of your choice.

Slide 4: Prerequisite To practice this tutorial, you should have gone through the earlier awk tutorials on this website.


You should have some knowledge of any programming language like C or C++.


If not, then please go through the corresponding tutorials on our website.

Slide 5: Code Files The files used in this tutorial are available in the Code Files link on this tutorial page.


Please download and extract them.

Slide 6: User defined functions Now let us learn about user defined functions.


The function syntax is as follows.


And the syntax is self-explanatory.

In Slide 6, highlight function keyword Here the keyword function is mandatory.
Slide 7: Function Call To call a function, write the name of the function, followed by the arguments in parentheses.


Note: space is not allowed between the function name and the open parentheses of the argument.

Slide 8: Example We will see one example now.


Now, in our awkdemo.txt file, the sixth field represents stipend.


Assume that stipend is either zero or consists of four digits.


Suppose, stipend is 8900.

  • Print it as 8 thousand 9 hundred in words.
  • If stipend is 0, print as zero in words.
Show user_function.awk in gedit I have already written the code in a file named user_function.awk
Highlight function changeit(argval) Here I have written a function named changeit with a single argument argval.


Here argval is basically our sixth field which is stipend.

Highlight if(argval==0) Inside the function, first the code will check if argval is zero or not.
Highlight printf("zero") If yes, it will print “Zero”
Highlight else part If not, then the else part of the code will be executed.
Highlight


a[1]=substr(value,1,1)

a[2]=substr(value,2,1)

a[3]=substr(value,3,1)

a[4]=substr(value,4,1)

In the else part, first we will extract each digit one by one using the substr function.


And we'll store the values in an array a at different indices.

Highlight a[1]=substr(value,1,1) For example, a[1] will give the first digit from left hand side or the thousand’s place digit.


Since we have only four digits, I used four indices.

Highlight all the if loops inside else block Next, we will check whether the elements are not equal to zero.


And print them in a proper order.

Highlight printf("\n") At the end, we print a backslash n character, to provide new line break in the output.
Highlight $2 in the last print statement Then inside the awk script, we have printed dollar 2, which is the second field that is name.
Highlight changeit($6) Then we call the function changeit with the parameter dollar 6, which is stipend.


Let’s execute the file.

Switch to terminal >> cd into the saved folder. Switch to the terminal.


Next go to the folder where you have downloaded and extracted the file, using cd command.

Type:


awk -F "|" -f user_function.awk awkdemo.txt

[Enter]

Now type the following command and press Enter.
Show the output We get the output as expected.
Slide 9: Return statement A user-defined function can also include a return statement.


This statement returns control to the calling part of the awk program.


It can also be used to return a value for use in the rest of the awk program.

Slide 9: Return statement It looks like this:return space expression


Here the expression part is optional.

Let’s write a function to return average of an array.
Show in gedit average.awk


I have written the code in the file average.awk


Let’s view the contents.

Highlight appropriately in

function avg(arr, i, sum,n,ret)


We have defined a function named avg for this purpose.


It has five parameters.


arr is the array for which the average is to be calculated.


i is array loop variable.


sum is the summation of all array elements.


n indicates the number of elements in array.


ret represents the variable to be returned from the function avg.


ret will store the calculated average.

Highlight extra space

function avg(arr, i, sum,n,ret)

The extra space before i indicates that the variables i, n, sum and ret are local variables.


Actually, the local variables are not intended to be arguments.


You should follow this convention when defining functions.

Highlight inside

for (i in arr) {

n++

sum += arr[i]

}

Inside the for loop, we have calculated the total number and summation of array elements.
Highlight

ret=sum/n

return ret

We have calculated the average by dividing summation with the total number of elements.


And stored that value in variable ret.


This function avg() returns the value of the variable ret.

Highlight appropriately in the file Inside the BEGIN section, we have defined array nums with 5 different numbers.
Highlight

print avg(nums)

In the print statement, we call the function avg() with one argument, which is the array name.


So, you do not have to pass local variables as arguments.

Switch to the terminal. Switch back to the terminal.


Let me clear the terminal.

Type at command prompt

awk -f average.awk

[Enter]

Type the following command-

awk space hyphen f space average dot awk


And press Enter.

Show the output We get the output as 3.6.


You can validate it by using a calculator.

Let us look at one more example.
Show reverse.awk in Gedit I have written a code to reverse a string and named it as reverse.awk


recursive function is used to reverse a string.


Pause the video here and look at the code to understand how the control flows.


Then execute it to see the output.

Display Slide As an assignment, use the function rev to reverse the Roll number field in awkdemo.txt file.


For example, if the roll number is A001, output should be 100A.


The code for the same is provided as reverse_roll.awk in the Code Files link.

Display Slide 9

Summary

This brings us to the end of this tutorial.


Let us summarize.


In this tutorial we learnt about-

  • The syntax of function definition
  • Function call and
  • Return statement
Display Slide 10

Assignment


As an assignment-


1. Write a function to create a transpose of a 2D matrix.

2. Write a function to return the minimum value element from an array.

Display Slide 11

About Spoken Tutorial project

The video at the following link summarises the Spoken Tutorial project.

Please download and watch it.

Display Slide 12

Spoken Tutorial workshops

The Spoken Tutorial Project team conducts workshops using spoken tutorials.


And gives certificates on passing online tests.


For more details, please write to us.

Display Slide 13

Forum for specific questions:

Please post your timed queries in this forum.
Display Slide 14

Acknowledgement

Spoken Tutorial Project is funded by NMEICT, MHRD, Government of India.


More information on this mission is available at

this link.

The script has been contributed by Antara.


And this is Praveen from IIT Bombay signing off.

Thank you for joining

Contributors and Content Editors

Antarade, Nancyvarkey