Shell – awk with if statements

awkscriptingshell

I am trying to print from a file using awk, but my output is empty.
Here is my code so far

accountNum=$1
while read -r LINE || [[ -n $LINE ]] ; do
            awk -F',' '{ if($1==accountNum) { print $3.$2 } }' Accounts
done < Accounts

I have also tried this:

accountNum=$1
while read -r LINE || [[ -n $LINE ]] ; do
            echo $LINE  | awk -F',' '{ if($1==accountNum) { print $3.$2 } }' 
done < Accounts

The input file is :

1,Doe,John
2,Rooney,Wayne
3,Smith,Will
4,Crow,Russel
5,Cruise,Tom

The expected output when I run the file is

$./file.sh 3
Will Smith

But I get the following

$./file.sh 3
$

That is nothing is being printed out. I know the solution with cut, but I want to use awk.

Best Answer

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.

Related Question