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
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
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?
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.
From man awk
we have that:
-v var=val
--assign var=val
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.
Then we read in Using Variables in a Program that:
The name of a variable must be a sequence of letters, digits, or underscores, and it may not begin with a digit.
Variables in awk can be assigned either numeric or string values.
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.