There are many common functions (especially arithmetic/mathematics) that are not built into awk
that I need to write myself all the time.
For example:
- There is no
c=min(a,b)
, so inawk
i constantly writec=a<b?a:b
- same for maximum i.e.
c=max(a,b)
- same for absolute value i.e.
c=abs(a)
so i have to constantly writec=a>0?a:-a
- and so on....
Ideally, I could write these functions into an awk
source file, and "include" it into all of my instances of awk, so I can call them at will.
I looked into the "@include" functionality of GNU's gawk
, but it just executes whatever is in the included script - i.e. I cannot call functions.
I was hoping to write some functions in e.g. mylib.awk
, and then "include" this whenever I call awk
.
I tried the -f mylib.awk
option to awk
, but the script is executed - the functions therein are not callable.
With GNU awk you can use the -i command line option or from inside a script the @include directive, but if you want a POSIX solution then awk -f functions.awk -f script.awk file.txt is the way you need to go.
on regular awk (non gnu) you can still fake a bit using the shell using a cat of the file(s) into the 'code' (generally in front, but could be everywhere since it respect the awk way of working order)
In case if you can't use
-i
(if yourawk < 4.1
version ), which EdMorton suggested, make a try of below works withGNU Awk 3.1.7
With GNU awk:
You can have multiple
-f program-file
options, so one can be your common functions and the other can be a specific problem solving awk script, which will have access to those functions.I don't know if this is what you were looking for, but it's the best I've come up with. Here's an example:
With regular awk (non-gnu) you can't mix the
-f program-file
option with an inline program. That is, the following won't work:As pointed out in the comments, however, with gawk you can use the
-f
option together with-e
: