Processing variable values using awk

Hello,

I am using the command below to send emails to users using a for loop. If The command finds the user Id in 1st column then it will print the email Id of the user from the 2nd column.

/usr/bin/awk -F "," ' $1 == "username"  {print $2}' file.csv

This command is getting executed when I give the username directly or execute it manually in command line. But when I try to use the same code in shell script to process various usernames in a for loop, the awk command doesn't recognize the variables

The code I am using in shell script is below. Can someone please let me know how to fix this?

For usr in ${users[@]}; do
/usr/bin/awk -F "," ' $1 == "$usr"  {print $2}' file.csv
done > out.txt

No surprise. Shells don't expand variables enclosed in single quotes. Use awk 's standard mechanism to convey variables: the -v option. Like

awk -F "," -v"USER=$usr" ' $1 == USER  {print $2}' file.csv

BTW, it may not seem the wisest use of resources to open, work through, and close the file for every single username in your array. Better do it all in one tool, e.g. awk , like e.g.

echo ${users[@]} | awk 'NR==1 {for (i=1; i<=NF; i++) T[$i]++; next} $1 in T {print $2}' - FS=, file.csv
2 Likes