1

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.

3
  • 5
    gnu.org/software/gawk/manual/html_node/… Commented Sep 26, 2014 at 15:31
  • As the link @Basilevs posted states, you can use @include "file" to import files. Commented Sep 26, 2014 at 16:26
  • 1
    I guess you could also alias awk to awk -i funcs.awk Commented Sep 26, 2014 at 16:28

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

but then I have to do this every time... i suppose Mark Setchell's comment is best
For your specific use, perhaps it is best. It depends how you want to call awk. It might make sense to only include it for the specific awk programs which need the external functions. Also, if using an awk script, it seems more practical to do all the @includes at the top instead of passing each to the -i command line argument.
1

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)}' 

1 Comment

This was so helpful. I was missing the --source bit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.