AWK-以指令执行字串吗? [英] AWK - execute string as command?

查看:59
本文介绍了AWK-以指令执行字串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此命令将打印:

$ echo "123456789" | awk '{ print substr ($1,1,4) }'
1234

是否可以将字符串作为命令执行?例如,以下命令:

Is it possible to execute a string as command? For example, this command:

echo "123456789" | awk '{a="substr"; print a ($1,1,4) }'

结果:

$ echo "123456789" | awk '{a="substr"; print a ($1,1,4) }'
awk: {a="substr"; print a ($1,1,4) }
awk:                               ^ syntax error

$ cat tst.awk 
function my_substr(x,y,z) { return substr(x,y,z) }

{ a="my_substr"; print @a($1,1,4) }
bolek@bolek-desktop:~/Pulpit$ echo "123456789" | gawk -f tst.awk
gawk: tst.awk:3: { a="my_substr"; print @a($1,1,4) }
gawk: tst.awk:3:                        ^ nieprawidłowy znak '@' w wyrażeniu
bolek@bolek-desktop:~/Pulpit$ 

推荐答案

您可以使用间接函数调用通过GNU awk中的变量来调用用户定义的函数,请参见

You can call user-defined functions via variables in GNU awk using indirect function calls, see http://www.gnu.org/software/gawk/manual/gawk.html#Indirect-Calls

$ cat tst.awk
function foo() { print "foo() called" }
function bar() { print "bar() called" }

BEGIN {
   the_func = "foo"
   @the_func()

   the_func = "bar"
   @the_func()
}
$ gawk -f tst.awk
foo() called
bar() called

不幸的是,由于内部实现问题,如果要以这种方式调用内置函数,则需要为每个函数编写一个包装器:

Unfortunately due to internal implementation issues, if you want to call builtin functions that way then you need to write a wrapper for each:

$ cat tst.awk
function my_substr(x,y,z) { return substr(x,y,z) }

{ a="my_substr"; print @a($1,1,4) }
$ echo "123456789" | gawk -f tst.awk
1234

这篇关于AWK-以指令执行字串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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