awk with if statements

You should use -v option of awk:

awk -F',' -v accNum="$1" '$1 == accNum {print $3,$2}'

With $1 in double quote, the shell will handle all its special character ( if has ) for you.


You have:

accountNum=$1
awk -F',' '{ if($1==accountNum) { print $3.$2 } }' Accounts

How does the shell variable accountNum get into awk? It doesn't: you need to provide its value to awk explicitly. You can use:

awk -F',' '{ if($1=='"$accountNum"') { print $3.$2 } }' Accounts

which leaves single quotes and has the shell substitute the value of its variable into the awk command, then reenters single quotes for the rest of the command string.

A better or at least more idiomatic script would be:

#!/bin/sh
accountNum=$1
awk -F, '$1 == "'"$accountNum"'" { print $3,$2 }' Accounts

which deals with non-numeric account numbers (quoting the substituted variable), uses a pattern block instead of an explicit if (the {} block will run if the test before it is true), and prints a space between the names as you wanted (because of ,). If you prefer to use if explicitly, move the test inside your existing if statement.

Depending on your real goal awk may not be the best fit for what you're doing. The above still fails if the script's $1 has quotes in it. The shell loop you had wasn't doing anything useful, although it would have repeated the output many times.


Your script already practically does the job without any awk at all:

while IFS=, read -r num last first
    do  [ $((num==accountNum)) -eq 1 ] && 
        printf '%s.%s\n' "$first" "$last"
done < Accounts

I'm not suggesting that this is a better or more efficient solution than using awk alone, but if you want the while...read loop, this certainly beats separate awk processes per each line. Just an FYI, I guess.