Using variable in awk command

Have a small doubt .
While using an iterator , i need to take the fields as seen as below .
But the Iterator is not been displayed . Can you please help with this .

Code:

ITERATOR=0COUNT=`cat test.txt`echo "$COUNT" while [ $ITERATOR -lt $COUNT ]do echo $ITERATOR echo "$COUNT" awk 'NR=="$ITERATOR"{print;exit}' EMAIL_REPORT.CSV >temp_mail.txt TO=`cat temp_mail.txt` ITERATOR=`expr $ITERATOR + 1`done

By using set -x , i checked the data been sent .

Code:

+ awk NR=="$ITERATOR"{print;exit} EMAIL_REPORT.CSV
 

Can you please help with this .

After reformatting your script

ITERATOR=0
COUNT=`cat test.txt`
echo "$COUNT"

while [ $ITERATOR -lt $COUNT ]
do
    echo $ITERATOR
    echo "$COUNT"
    awk 'NR=="$ITERATOR" {print;exit}' EMAIL_REPORT.CSV >temp_mail.txt
    TO=`cat temp_mail.txt`
    ITERATOR=`expr $ITERATOR + 1`
done

you can see, that your awk script is enclosed in single quotes. They prevent variable expansion, so awk sees the literal text $ITERATOR . Also, since $ITERATOR is supposed to be a number, you don't need the double quotes.

awk 'NR=='$ITERATOR' {print;exit}' EMAIL_REPORT.CSV >temp_mail.txt

As did the other (faster) poster, I tried reformatting the script to make it easier to read, and to make the logic work (as it seemed to me). You can correct if I mixed something up.

ITERATOR=1
COUNT=`tail -1 test.txt`
echo COUNT = $COUNT
while [ $ITERATOR -le $COUNT ]; do
  echo ITERATOR = $ITERATOR
  awk -v i=$ITERATOR 'NR == i {print; exit}' EMAIL_REPORT.CSV > temp_mail.txt
  # sed -n "$ITERATOR { p; q }" EMAIL_REPORT.CSV > temp_mail.txt
  TO=`cat temp_mail.txt`
  ITERATOR=`expr $ITERATOR + 1`
done

As the other poster stated, the problem is because the awk script is enclosed in 'single quotes'. So awk just sees the literal $ITERATOR. In other words, the shell variable is not expanded.

If your version of awk supports the -v option, I've suggested a nice alternative way to make it work. I couldn't get the other submitted script to work, but I'm probably messing it up. I hope at least one of them works for you! :slight_smile:

Instead of using awk to print the one line, you could also use the simpler sed command I added.

1 Like

Thanks a lot worked perfectly ...