简体   繁体   中英

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. How do I insert ${user[$i]} into the AWK command.

As I noted in a comment , you have your Awk script enclosed in single quotes; your shell variables will not be expanded inside the single quotes. On the whole, that's good; $NF is not one of your shell variables.

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.


There are a few other oddities in the script. The < is not necessary with cat . You could avoid the Bash array by using:

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. Fortunately, you redirect the standard output to a file so the string executed is empty, and nothing happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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