Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I know the -v switch can be used to awk on the command line to set the value for a variable.

Is there any way to set values for awk associative array elements on the command line?

Something like:

awk -v myarray[index]=value -v myarray["index two"]="value two" 'BEGIN {...}'
share|improve this question
up vote 5 down vote accepted

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.

share|improve this answer
    
Thanks, I like your first option better than the gawk specific one—I almost always stick to POSIX features. I think I would also use printf in preference to echo. – Wildcard Jan 12 at 22:20

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.