在awk中包含函数库 [英] include library of functions in awk
问题描述
awk
中没有内置许多常用功能(尤其是算术/数学),我需要一直写自己.
There are many common functions (especially arithmetic/mathematics) that are not built into awk
that I need to write myself all the time.
例如:
- 没有
c=min(a,b)
,所以在awk
中,我不断地写c=a<b?a:b
- 最大相同,即
c=max(a,b)
- 绝对值相同,即
c=abs(a)
,所以我必须不断写c=a>0?a:-a
- 以此类推....
- 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....
理想情况下,我可以将这些函数写到awk
源文件中,然后将其包含"到我的所有awk实例中,这样我就可以随意调用它们.
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.
我研究了GNU gawk
的"@include"功能,但是它只是执行包含脚本中的任何内容,即我无法调用函数.
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.
我希望写一些函数,例如mylib.awk
,然后每当我调用awk
时包含"此内容.
I was hoping to write some functions in e.g. mylib.awk
, and then "include" this whenever I call awk
.
我尝试了awk
的-f mylib.awk
选项,但是脚本已执行-其中的函数不可调用.
I tried the -f mylib.awk
option to awk
, but the script is executed - the functions therein are not callable.
推荐答案
使用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
这篇关于在awk中包含函数库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!