Set awk array on command line?

Wil*_*ard 7 shell options awk associative-array

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 {...}'
Run Code Online (Sandbox Code Playgroud)

joe*_*epd 7

不。不可能在命令行上分配像这样的非标量变量。但要做到这一点并不难。

如果您可以接受固定的数组名称:

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

如果您有一个包含数组定义的 awk 语法的文件,您可以include:

$ 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]}'
Run Code Online (Sandbox Code Playgroud)

或者

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

如果你真的想要,你可以gawk使用-E而不是运行-f,这会给你一个未解释的命令行。然后您可以处理这些命令行选项(如果它看起来像一个变量赋值,则赋值该变量)。如果您想走那条路,查看ngetopt.awk可能会有所帮助。