Set awk array on command line?

No. It is not possible to assign non-scalar variables like this on the command line. But it is not too hard to make it.

If you can accept a fixed array name:

awk -F= '
  FNR==NR { a[$1]=$2; next}
  { print a[$1] }
' <(echo $'index=value\nindex two=value two') <(echo index two)

If you have a file containing the awk syntax for array definitions, you can include it:

$ cat <<EOF >file.awk
ar["index"] = "value"
ar["index two"] = "value two"
EOF

$ gawk '@include "file.awk"; BEGIN{for (i in ar)print i, ar[i]}'

or

$ gawk --include file.awk 'BEGIN{for (i in ar)print i, ar[i]}'

If you really want, you can run gawk with -E rather than -f, which leaves you with an uninterpreted command line. You can then process those command line options (if it looks like a variable assignment, assign the variable). Should you want to go that route, it might be helpful to look at ngetopt.awk.


With POSIX awk, you can't do it.

The assignment in form -v assignment was defined as:

An operand that begins with an or alphabetic character from the portable character set (see the table in XBD Portable Character Set), followed by a sequence of underscores, digits, and alphabetics from the portable character set, followed by the '=' character, shall specify a variable assignment rather than a pathname. The characters before the '=' represent the name of an awk variable; if that name is an awk reserved word (see Grammar) the behavior is undefined

That's only allow awk variable name.

When you set awk array element with:

myarray[index]=value

myarray[index] is lvalue, not variable name. So it's an illegal.

Any variables and fields can be set with:

lvalue = expression

with lvalue can be variables, array with index or fields selector.