Skip to content

User defined functions

Related Awk documentation

Usually at this point (looking on how to write own functions) you have a working script (I doubt you want to do this on one line) and you want to wrap your repetitive task in a function call...
The User defined function syntax is as follows

function name([parameter-list])
{
  body-of-function

  [return variable] 
}

Here is a simple example.
It is rather surprising but awk dows not have funtion to return athe absolute value of a number.

function abs(x){
  if (x >= 0) return x
  else return -x
}

or

function abs(x)  { return (x >= 0) ? x : -x }

Here is another example from one of the study cases Gaussian smearing
Gaussian funtion. I have used \(x_0\) instead of \(b\) for the peak center.

function gauss(x0,x,c){
  area=1;
  if ((x-x0)**2 < 10000) { return  area*exp(-(((x-x0))**2)/(2.*c**2))}
  else {return 0.0}
}

The function returns the value for the Gaussian for a point \(x\) away from the center. For large \((x-x0)^2\) the exp() was crashing, so I needed to add a condition which makes sure that for these very large numbers the function does not call the exp(...) but returns directly 0.0 instead. The function is called within a double loop on line 23

23
      data[i]= data[i] + gauss(freq[f],i,FWHM);

Warning

It's entirely fair to say that the awk syntax for local variable definitions is appallingly awful.
- Brian Kernighan source