我可以使用-v将数组传递给awk吗? [英] Can I pass an array to awk using -v?

查看:125
本文介绍了我可以使用-v将数组传递给awk吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将数组变量传递给awk.我不是说一个shell数组,而是一个本机的awk数组.我知道我可以像这样传递标量变量:

I would like to be able to pass an array variable to awk. I don't mean a shell array but a native awk one. I know I can pass scalar variables like this:

awk -vfoo="1" 'NR==foo' file

我可以使用相同的机制来定义awk数组吗?像这样:

Can I use the same mechanism to define an awk array? Something like:

$  awk -v"foo[0]=1" 'NR==foo' file
awk: fatal: `foo[0]' is not a legal variable name

我已经尝试了上述几种变体,但是它们都无法在我的Debian上的GNU awk 4.1.1上运行.那么,是否有任何awk版本(gawkmawk或其他任何版本)可以从-v开关接受数组?

I've tried a few variations of the above but none of them work on GNU awk 4.1.1 on my Debian. So, is there any version of awk (gawk,mawk or anything else) that can accept an array from the -v switch?

我知道我可以解决此问题,并且可以轻松地想到实现此目的的方法,我只是想知道是否有任何awk实现本身都支持这种功能.

I know I can work around this and can easily think of ways to do so, I am just wondering if any awk implementation supports this kind of functionality natively.

推荐答案

从定义上看,这似乎是不可能的.

It looks like it is impossible by definition.

man awk中,我们有:

-v var = val

-v var=val

-分配var = val

--assign var=val

在执行之前,将值val分配给变量var 程序开始.这样的变量值可用于BEGIN规则 AWK程序.

Assign the value val to the variable var, before execution of the program begins. Such variable values are available to the BEGIN rule of an AWK program.

然后我们阅读在程序中使用变量该:

变量名称必须是字母,数字或 下划线,并且不能以数字开头.

The name of a variable must be a sequence of letters, digits, or underscores, and it may not begin with a digit.

awk中的变量可以分配数字值或字符串值.

Variables in awk can be assigned either numeric or string values.

因此,定义-v实现的方式使其无法提供数组作为变量,因为=[字符的任何形式的使用都不允许作为-v变量的一部分通过.而且这两个都是必需的,因为awk中的数组仅是关联的.

So the way the -v implementation is defined makes it impossible to provide an array as a variable, since any kind of usage of the characters = or [ is not allowed as part of the -v variable passing. And both are required, since arrays in awk are only associative.

这篇关于我可以使用-v将数组传递给awk吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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