cmo
cmo

Reputation: 4114

awk: automatically call functions from file

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

Answers (2)

Akshay Hegde
Akshay Hegde

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

John B
John B

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

Related Questions