awk help (external variable)

i need help with an awk question. i am looking to have an external variable be defined outside of awk but used in awk. so if we have fields $1, $2, $3 so on and so forth, i would like to be able to dictate what field is being printed by something like $[i]. so if i had a counter called test, make it 3 so the awk line would read `awk -F, '{ if ($[test] == "Annual") print $2}'. thus printing field 2 if field 3 equals Annual.

i hope i've somehow explained what i'm looking for. any thoughts, ideas, suggestions would be awesome. note that i am calling awk from within a function. call from case looks like this:

"02") get_jan_info "$(echo ${userpri[@]})" "$(echo ${usersec[@]})";;

code is here:

get_jan_info() {
        for pri_user in `awk -F, '{ if ($3 == "Annual") print $2;}' review.csv`
        do
               userpri[$num]=$pri_user  
               let "num = $num + 1"
        done

... #more that isn't relevant. 
}

thanks in advance.

Yes, it is possible to do what you want to do. Here is a simple example
which demonstrates how to do it

#!/usr/bin/ksh

tmp=file.$$

cat <<EOT >$tmp
Annual 222 333 444
EOT

awk 'BEGIN { test=1; } { if ($test == "Annual") print $2 }' $tmp

rm $tmp

exit 0

thanks for the quick reply. i'll go check that out right now.

ok. however, i need test to be declare and defined outside of awk. such as:

get_jan_info() {
  test=3;
  for pri_user in `awk -F, 'BEGIN {if ($test == "Annual") print $2;}' review.csv`

actually, its very similar to what this guy is trying to do.

pass variable to awk - The UNIX Forums

It's not clear what you're trying to achieve but with awk you can't print a field of the input in the BEGIN section, only actions you want to perform before the first line of input is read.

Regards

OK, I have modified my previous example to show you how to do what you now want to do

#!/usr/bin/ksh

tmp=file.$$

cat <<EOT >$tmp
Annual 222 333 444
EOT

awk -v tt=1 'BEGIN { test=tt; } { if ($test == "Annual") print $2 }' $tmp

rm $tmp

exit 0

if gotten the idea of getting variables passed to awk. thats a good start :slight_smile: :slight_smile: however, it doesn't print field 3 ($3). it just doesn't actually pass the condition. i think it just does a if 3=annual and fails. any other ideas??

seriously... thanks for this much so far. really do appreciate it because i'm banging my head against the desk as we speak!

get_jan_info() {
test='3'
echo $test
        for pri_user in `awk -vfield3="$test" -F, 'print $field3 {if ($field3 == "Annual") print $2;}' review
.csv

It is working for me. But I use nawk, not just awk!

>echo "abs do aaa bbb\n 111 222 333 444"| nawk -v nn=3 '{if ( $nn == "aaa" ) print $2; else print $1;}'
do
111