• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • VCS
  • Interview Questions
  • Database
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

How to Use user-defined Functions in awk

by admin

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 }

Filed Under: DevOps, Shell Scripting

Some more articles you might also be interested in …

  1. “docker save” Command Examples
  2. Examples of “shift” Command in Shell Scripts
  3. ValueError: Masked arrays must be 1-D
  4. “docker container” Command Examples
  5. How to List / Start / Stop / Delete docker Containers
  6. How to install Docker on Mac
  7. “docker system” Command Examples
  8. Endpoint is not Created for Service in Kubernetes
  9. How to Trace Python Scripts using trace.py
  10. Bash if loop examples (if then fi, if then elif fi, if then else fi)

You May Also Like

Primary Sidebar

Recent Posts

  • glab Command Examples
  • “glab repo” Command Examples
  • “glab release” Command Examples
  • “glab pipeline” Command Examples

© 2023 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright