Shell variable as awk condition

Hi,

I'm trying to automate part of a script which uses awk to grab out some lines of a log file based on certain fields matching. For example, my log file looks something like the following (but 1000s of lines):

1 Tom 123 abc 345
2 Dick 345 abc 678
3 Harry 567 abc 345
4 Tom 345 cde 345
5 Harry 123 cde 567

My script simply uses awk to grab the second field being 345 or 123 for example:

awk '$2 == "345" || $2 == "123" log.file

However, the 345 or 123 is dynamic, so what I'd like is to replace the awk condition with a shell variable, i.e. something like the following

awk -v SHELLVAR=${DYNAMIC} 'SHELLVAR' log.file

Where $DYNAMIC would be as follows, generated elsewhere in the script:

$2 == "345" || $2 == "123"

I've tried various things around the above, but just get every line from the log file rather than selecting out those that match as per $DYNAMIC

I'm probably missing something really obvious here - Any ideas?

well your $2 is names in this example, so that should be $3. the proper way to pass and use variables follows:

$ value=345
$ awk -vn="$value" '$3 == n' file
2 Dick 345 abc 678
4 Tom 345 cde 345

what you describe is using a shell variable to hold an awk program.

mute@thedoctor:~$ code='$3 == 345 || $3 == 123'
mute@thedoctor:~$ awk "$code" file
1 Tom 123 abc 345
2 Dick 345 abc 678
4 Tom 345 cde 345
5 Harry 123 cde 567

Well that's embarrassing! I'm sure I tried that in the very first instance, but it didn't work, hence trying to over complicate it! I must have got my code slightly wrong.

Thanks!

You could also try (simplified "code" assignment):

code='345|123'
awk -vCOD="$code" '$3 ~ "^("COD")$"' file