7

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 {...}'

3 Answers 3

7

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.

1
  • 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, 2016 at 22:20
2

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.

0

How's this?

awk _F";" -v M=JanFebMarAprMayJunJulAugSepOctNovDec '$1>=180525 && $1<=180630\
{ m=substr($1,3,2); m=(m-1)*3+1; printf(" %s %d, 20%d\t%s\n",substr(M,m,3),\
substr($1,5,2),substr($1,1,2),$0);}' Filename

File delimited with ";". First field is date formated yymmdd. Use string as array. Is this cheating?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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