awk == with a variable

korn shell script on a Solaris 10 system

for NUM in 1234 1235; do cat <file> |awk -F\; '$7==$NUM {print $0}' ; done

If the numbers 1234 or 1235 appear in the 7th column, print the line

this works

for NUM in 1234 1235; do cat <file> |awk -F\; '$7==1234 {print $0}' ; done

but when I try to put a variable in it doesn't like it. I have tried to protect my $NUM variable using ${NUM" or $"{NUM}" but no joy.

any ideas?

for NUM in 1234 1235
do
   nawk -F\; '$7==n' n="${NUM}" myFile
done
1 Like

Thing I don't like about this is your file is being read once for each value of NUM. Where are these NUM values comming from (hardcoded, output of some other command, commandline input, etc)?

If we knew that it should be possible to get a nawk command then reads the file once and prints any line that matches your list of required values.

for example:

nawk '$7 ~ N' N="1234|1235" myFile

Not sure if this works with korn on solaris, but you could build a regex with your numbers and have awk compare $7 against it:

NUM=1234\|1235;awk  '$7~/'$NUM'/ {print $0}' file

Of course you can drop the {print $0}, as Chubler_XL posts...

Here is what my final code looks like once I had cleaned it up

 nawk -F\; '$7==n' n="${NUM}" file

$7 is the column I want to search for a specific number. This number may exist in other columns in the file so I want to be specific that the $NUM must be in the 7th position.
$NUM contains a list of numbers I want to search for

1 Like

You cannot use == on a list of numbers. It will check if column 7 is equal to "1234 1235", see that it isn't, and return false. You'll have to split it in the BEGIN section. If you put it in an array like B["12345"]=1, you can check without a loop.

Since you need it in the BEGIN section, you will have to put the variable in with -v before, not VAR= afterwards. When you put in variables at the end, they get assigned when awk starts reading files, after BEGIN happens.

awk -v N="1234 5678" 'BEGIN { split(N,X); for(L in X) B[A[X]]=1 } $7 in B' inputfile