Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using awk for a table lookup

Tags:

awk

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

like image 699
user534805 Avatar asked Dec 08 '10 09:12

user534805


2 Answers

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
like image 197
Dennis Williamson Avatar answered Oct 12 '22 23:10

Dennis Williamson


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.

like image 30
Chris J Avatar answered Oct 13 '22 01:10

Chris J