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 which 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:
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
This function deletes all the elements in an array.
function delarray(a, i) { for (i in a) delete a[i] }
When working with arrays, it is often necessary to delete all the elements
in an array and start over with a new list of elements
(see section The delete
Statement).
Instead of having
to repeat this loop everywhere in your program that you need to clear out
an array, your program can just call delarray
.
Here is an example of a recursive function. It takes a string as an input parameter, and returns the string in backwards order.
function rev(str, start) { if (start == 0) return "" return (substr(str, start, 1) rev(str, start - 1)) }
If this function is in a file named `rev.awk', we can test it this way:
$ echo "Don't Panic!" | > gawk --source '{ print rev($0, length($0)) }' -f rev.awk -| !cinaP t'noD
Here is an example that uses the built-in function strftime
.
(See section Functions for Dealing with Time Stamps,
for more information on strftime
.)
The C ctime
function takes a timestamp and returns it in a string,
formatted in a well known fashion. Here is an awk
version:
# ctime.awk # # awk version of C ctime(3) function function ctime(ts, format) { format = "%a %b %d %H:%M:%S %Z %Y" if (ts == 0) ts = systime() # use current time as default return strftime(format, ts) }
Go to the first, previous, next, last section, table of contents.