在awk中包含函数库 [英] include library of functions in awk

查看:123
本文介绍了在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.

例如:

  1. 没有c=min(a,b),所以在awk中,我不断地写c=a<b?a:b
  2. 最大相同,即c=max(a,b)
  3. 绝对值相同,即c=abs(a),所以我必须不断写c=a>0?a:-a
  4. 以此类推....
  1. There is no c=min(a,b) , so in awk i constantly write c=a<b?a:b
  2. same for maximum i.e. c=max(a,b)
  3. same for absolute value i.e. c=abs(a) so i have to constantly write c=a>0?a:-a
  4. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆