Here is an example of a user-defined function, called myprint(), that
takes a number and prints it in a specific format:
function myprint(num)
{
printf "%6.3g\n", num
}
To illustrate, here is an awk rule that uses our myprint()
function:
$3 > 0 { myprint($3) }
This program prints, in our special format, all the third fields that contain a positive number in our input. Therefore, when given the following input:
1.2 3.4 5.6 7.8 9.10 11.12 -13.14 15.16 17.18 19.20 21.22 23.24
this program, using our function to format the results, prints:
5.6 21.2
The following is an example of a recursive function. It takes a string as an input parameter and returns the string in reverse order. Recursive functions must always have a test that stops the recursion. In this case, the recursion terminates when the input string is already empty:
function rev(str)
{
if (str == "")
return ""
return (rev(substr(str, 2)) substr(str, 1, 1))
}
If this function is in a file named rev.awk, it can be tested this way:
$ echo "Don't Panic!" |
> gawk -e '{ print rev($0) }' -f rev.awk
⊣ !cinaP t'noD
Another example of a recursive function comes from high-school mathematics. The factorial of a number N, is defined as shown in Table 9.7:
| Value of N | Result |
|---|---|
| N <= 0 | Error |
| N = 1 | 1 |
| N > 1 | N * factorial(N − 1) |
Table 9.7: Definition of factorial()
For factorial(), the test that stops the recursion is if N
equals one. Here’s the code:
# factorial --- print the factorial of N
function factorial(n)
{
if (n <= 0)
return -1 # bad input
if (n == 1)
return n
return n * factorial(n - 1)
}
{ print factorial($0) }
Here are the results of running this program with BWK awk
and gawk:
$ nawk -f factorial.awk 4 ⊣ 24 3 ⊣ 6 42 ⊣ 1.40500611775287978877963579759e+51 $ gawk -f factorial.awk 4 ⊣ 24 3 ⊣ 6 42 ⊣ 1405006117752879788779635797590784832178972610527232
The C ctime() function takes a timestamp and returns it as a string,
formatted in a well-known fashion.
The following example uses the built-in strftime() function
(see Time Functions)
to create an awk version of ctime():
# ctime.awk
#
# awk version of C ctime(3) function
function ctime(ts, format)
{
format = "%a %b %e %H:%M:%S %Z %Y"
if (ts == 0)
ts = systime() # use current time as default
return strftime(format, ts)
}
You might think that ctime() could use PROCINFO["strftime"]
for its format string. That would be a mistake, because ctime() is
supposed to return the time formatted in a standard fashion, and user-level
code could have changed PROCINFO["strftime"].