简体   繁体   English

如何使 Awk 与 shell 脚本中的 Bash 数组变量一起使用?

[英]How do I make the Awk work with Bash array variables in a shell script?

user=(`cat < usernameSorted.txt`)
for (( i=0; i<${#user[@]}; i++ ))
do
    `awk '$1 == "${user[$i]}"{print $NF}' process.txt > CMD$i.txt`
done

This is how I had coded for using user array elements as the awk specifier.这就是我使用用户数组元素作为 awk 说明符的编码方式。 How do I insert ${user[$i]} into the AWK command.如何将 ${user[$i]} 插入 AWK 命令。

As I noted in a comment , you have your Awk script enclosed in single quotes;正如我在评论中指出的那样,您的 Awk 脚本用单引号括起来; your shell variables will not be expanded inside the single quotes.您的 shell 变量不会在单引号内展开。 On the whole, that's good;总的来说,这很好; $NF is not one of your shell variables. $NF不是您的 shell 变量之一。

You'll probably need to use a variation on the theme of:您可能需要使用以下主题的变体:

awk -v user="${user[$i]}" '$1 == user { print $NF }' process.txt > "CMD$i.txt"

where you refer to user as an Awk variable set from "${user[$i]}" on the command line.您在其中将user称为 Awk 变量,该变量是从命令行上的"${user[$i]}"设置的。


There are a few other oddities in the script.剧本中还有其他一些奇怪的地方。 The < is not necessary with cat . <对于cat不是必需的。 You could avoid the Bash array by using:您可以使用以下方法避免 Bash 数组:

i=0
for user in $(cat usernameSorted.txt)
do
    awk -v user="$user" '$1 == user { print $NF }' process.txt > "CMD$i.txt"
    ((i++))
done

You do not want the back-ticks around the Awk command.您不希望 Awk 命令周围出现反引号。 Fortunately, you redirect the standard output to a file so the string executed is empty, and nothing happens.幸运的是,您将标准 output 重定向到一个文件,因此执行的字符串为空,并且没有任何反应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM