user534805
user534805

Reputation: 63

Using awk for a table lookup

I would like to use awk to lookup a value from a text file. The text file has a very simple format:

text \t value
text \t value
text \t value
...

I want to pass the actual text for which the value should be looked up via a shell variable, e.g., $1.

Any ideas how I can do this with awk?

your help is great appreciated.

All the best, Alberto

Upvotes: 6

Views: 10597

Answers (4)

Dennis Williamson
Dennis Williamson

Reputation: 360683

You can do this in a pure AWK script without a shell wrapper:

#!/usr/bin/awk -f
BEGIN { key = ARGV[1]; ARGV[1]="" }
$1 == key { print $2 }

Call it like this:

./lookup.awk keyval lookupfile

Example:

$ cat lookupfile
aaa     111
bbb     222
ccc     333
ddd     444
zzz     999
mmm     888
$ ./lookup.awk ddd lookupfile
444
$ ./lookup.awk zzz lookupfile
999

This could even be extended to select the desired field using an argument.

#!/usr/bin/awk -f
BEGIN { key = ARGV[1]; field = ARGV[2]; ARGV[1]=ARGV[2]="" }
$1 == key { print $field }

Example:

$ cat lookupfile2
aaa     111     abc
bbb     222     def
ccc     333     ghi
ddd     444     jkl
zzz     999     mno
mmm     888     pqr
$ ./lookupf.awk mmm 1 lookupfile2
mmm
$ ./lookupf.awk mmm 2 lookupfile2
888
$ ./lookupf.awk mmm 3 lookupfile2
pqr

Upvotes: 7

Iain
Iain

Reputation: 4203

I think grep might actually be a better fit:

$ echo "key value
ambiguous correct
wrong ambiguous" | grep '^ambiguous ' | awk ' { print $2 } '

The ^ on the pattern is to match to the start of the line and ensure that you don't match a line where the value, rather than the key, was the desired text.

Upvotes: 0

Callie J
Callie J

Reputation: 31326

Something like this would do the job:

#!/bin/sh
awk -vLOOKUPVAL=$1 '$1 == LOOKUPVAL { print $2 }' < inputFile

Essentially you set the lookup value passed into the shell script in $1 to an awk variable, then you can access that within awk itself. To clarify, the first $1 is the shell script argument passed in on the command line, the second $1 (and subsequent $2) are fields 1 and 2 of the input file.

Upvotes: 6

lhf
lhf

Reputation: 72422

TEXT=`grep value file | cut -f1`

Upvotes: 0

Related Questions