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 {...}'
Wildcard
  • 36,499

3 Answers3

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.

joepd
  • 2,397
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.

cuonglm
  • 153,898
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?

steve
  • 21,892
Rick
  • 1