awk awk awk

Functions 1

awk has several built-in functions which are available in your scripts. They deal either with arithmetic, string, or basic I/O activity.

Typically you use them like this:

function(argument/s)

For example, the atan2 function requires two arguments, so would be written thus:

atan2(y,x)

The list of the arithmetic functions is as follows:

awk also allows us to write our own functions. For example, a typical requirement is a random integer, not a floating-point number.

A simple user-defined function could be:

function intRan(n)
{
	return int( rand() * n)
}

randint first gets a random number, then multiplys it by n. We then take the integer value of that number.

Here we print 10 random numbers between 0 and 99 ...

function intRan(n)
{
	return int( rand() * n)
}
BEGIN {
	for (i=1; i <= 10; i++) {
		printf "%s ",int(rand()*100) # 0..99
	}
}

On my system I get the following results:

functions1

This may be all you need, and is useful for debugging but there is a gotcha.

As in other languages with a similar function, the function generates numbers from the same starting number (seed) each time it is run. This means you would get the same results each time you ran the script. They will be random the first time, but exactly the same thereafter. Try it yourself to see.

Enter srand([x]). This sets the seed value to x.

function rant(n)
{
	return int(n * rand())
}
BEGIN {
	srand() # <-----
	for (i=1; i < 10; i++) {
		print rant(100)
	}
}

This will print a list of 10 random integers between 0 and 99 every time you run it, and they will always be different.

functions2

Note these numbers are printed vertically. That is the default print action, ending with a newline character. Horizontal lists are printed using printf.

srand() uses the time of day as the seed value, unless you give it a different value. This value also determines the upper limit of the number generated.

To generate numbers in other ranges, here are some examples:

printf "%s ",int(rand()*10) # 1..10
printf "%s ",int(rand()*100) # 0..99
printf "%s ",int(rand()*1000) # 0..999
printf "%s ",int(rand()*47677) # 0..47677

Remember that computers only generate pseudo-random numbers