bash 在 awk 中使用数组变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5400228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use array variable in awk?
提问by Dagang
A=(aaa bbb ccc)
cat abc.txt | awk '{ print , ${A[]} }'
I want to index an array element based on the $1, but the code above is not correct in awk syntax. Could someone help?
我想根据 $1 索引一个数组元素,但是上面的代码在 awk 语法中不正确。有人可以帮忙吗?
采纳答案by kurumi
If you are going to be hard-coding the Aarray, you can just initialize it in awk
如果您打算对A数组进行硬编码,则只需在awk
awk 'BEGIN{A[0]="aaa";A[1]="bbb"}{ print , A[] }' abc.txt
回答by geekosaur
You can't index a basharray using a value generated inside awk, even if you weren't using single quotes (thereby preventing bashfrom doing any substitution). You could pass the array in, though.
即使您没有使用单引号(从而防止进行任何替换),您也不能使用bash在 内部生成的值来索引数组。不过,您可以传入数组。awkbash
A=(aaa bbb ccc)
awk -v a="${A[*]}" 'BEGIN {split(a, A, / /)}
{print , A[] }' <abc.txt
Because of the split function inside awk, the elements of Amay not contain spaces or newlines. If you need to do anything more interesting, set the array inside of awk.
由于 awk 中的 split 功能, 的元素A可能不包含空格或换行符。如果您需要做任何更有趣的事情,请将数组设置在awk.
awk 'BEGIN {a[1] = "foo bar" # sadly, there is no way to set an array all
a[2] = "baz" } # at once without abusing split() as above
{print , a[] }' <abc.txt
(Clarification: bashsubstitutes variables beforeinvoking the program whose argument you're substituting, so by the time you have $1in awkit's far too late to ask bashto use it to substitute a particular element of A.)
(澄清: 在调用您要替换其参数的程序之前bash替换变量,因此当您进入时,要求使用它来替换 的特定元素为时已晚。)$1awkbashA
回答by George Freeman
Your awk program within single quotes cannot see the shell environment variable A. In general, you can get a little shell substitution to work if you use double quotes instead of single quotes, but that is done by the shell, before awk is invoked. Overall, it is heavy sledding to try to combine shell and awk this way. If possible, I would take kurumi's approach of using an awk array.
单引号内的 awk 程序看不到 shell 环境变量 A。通常,如果使用双引号而不是单引号,则可以进行一些 shell 替换,但这是在调用 awk 之前由 shell 完成的。总的来说,尝试以这种方式结合 shell 和 awk 是一种沉重的负担。如果可能,我会采用 kurumi 使用 awk 数组的方法。
Single quotes: an impenetrable veil. Double quotes: generally too much travail. So pick your poison: shell or awk. Otherwise: your code may balk.
单引号:难以穿透的面纱。双引号:通常太多的工作量。所以选择你的毒药:shell 或 awk。否则:您的代码可能会犹豫。
回答by yaeuge
You can also print each element of the array on separate line with printf and pipe it to awk. This code will simply print bash array (bash_arr) from awk:
您还可以使用 printf 在单独的行上打印数组的每个元素并将其通过管道传输到 awk。此代码将简单地从 awk 打印 bash 数组 (bash_arr):
bash_arr=( 1 2 3 4 5 )
printf '%s\n' "${bash_arr[@]}" |
awk ' { awk_arr[NR] = ##代码## }
END {
for (key in awk_arr) {
print awk_arr[key]
}
}'

