Include function library in awk

There are many common functions (especially arithmetic / math) that are not built into awkwhat I need to write all the time.

For instance:

  • No c=min(a,b), that's why awkI 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 write constantlyc=a>0?a:-a
  • etc....

Ideally, I could write these functions to the source file awkand include it in all my awk instances so that I can call them.

I looked at GNU gawk"@include" functionality , but it just does everything contained in the included script - that is, I cannot call functions.

I was hoping to write some functions, for example. mylib.awkand then “enable” it when I call awk.

I tried the parameter -f mylib.awk awk, but the script is executed - the functions there are not callable.

+4
source share
3 answers

With GNU awk:

$ ls lib
prims.awk

$ cat lib/prims.awk
function abs(num) { return (num > 0 ? num : -num) }
function max(a,b) { return (a > b ? a : b) }
function min(a,b) { return (a < b ? a : b) }

$ export AWKPATH="$PWD/lib"

$ awk -i prims.awk 'BEGIN{print min(4,7), abs(-3)}'
4 3

$ cat tst.awk
@include "prims.awk"
BEGIN { print min(4,7), abs(-3) }

$ awk -f tst.awk
4 3
+4
source

You can have several parameters -f program-file, so you can be your common functions, and the other may be a problem solving awk script that will have access to these functions.

awk -f common-funcs.awk -f specific.awk file-to-process.txt

I don’t know, this is what you were looking for, but this is the best I came up with. Here is an example:

$ cat common_func.awk
# Remove spaces from front and back of string
function trim(s) {
  gsub(/^[ \t]+/, "", s);
  gsub(/[ \t]+$/, "", s);
  return s;
}

$ cat specific.awk
{ print $1, $2 }
{ print trim($1), trim($2) }

$ cat file-to-process.txt 
abc    |    def   |

2$ awk -F\| -f common_func.awk -f specific.awk file-to-process.txt 
abc         def   
abc def

With regular awk (non-gnu), you cannot mix an option -f program-filewith a firmware. That is, the following will not work:

awk -f common_func.awk '{ print trim($1) }' file-to-process.txt # WRONG 

, , gawk -f -e:

awk -f file.awk -e '{stuff}' file.txt
+3

If you can’t use -i(if your version awk < 4.1) that Edmonton suggested, try belowGNU Awk 3.1.7

- source code of the program

Provide the source code of the program in the text of the program. This option allows you to mix the source code in files with the source code that you enter on the command line. This is especially useful when you have a library of functions that you want to use from command line programs.

$ awk --version
GNU Awk 3.1.7
Copyright (C) 1989, 1991-2009 Free Software Foundation.

$ cat primes.awk 
function abs(num) { return (num > 0 ? num : -num) }
function max(a,b) { return (a > b ? a : b) }
function min(a,b) { return (a < b ? a : b) }

$ awk -f primes.awk --source 'BEGIN{print min(4,7), abs(-3)}'
4 3
0
source

All Articles