Reputation: 4114
I need to perform the absolute value calculation a lot in awk
.
But absolute value is not built into awk
, so many of my awk
commands look like this:
awk 'function abs(x){return ((x < 0.0) ? -x : x)} { ...calls to "abs" .... }' file
Is there a way to store user-defined awk
functions in files, and have awk
automatically load these functions whenever it is called?
Something like setting an awk
"include" path or user-profile, much the same way you do for bash and other programs.
Upvotes: 1
Views: 1266
Reputation: 16997
Also try
$ cat function_lib.awk
function abs(x){
return ((x < 0.0) ? -x : x)
}
call function like this
$ awk -f function_lib.awk --source 'BEGIN{ print abs(-1)}'
Upvotes: 1
Reputation: 3646
You can use @include "file"
to import files.
e.g. Create a file named func_lib
:
function abs(x){
return ((x < 0.0) ? -x : x)
}
Then include it with awk
:
awk '@include "func_lib"; { ...calls to "abs" .... }' file
Upvotes: 1