Using awk to find a table

I would like to use awk to search for values ​​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 viewed through a shell variable, for example, $ 1.

Any ideas how I can do this with awk?

Your help is greatly appreciated.

All the best, Alberto

+4
source share
4 answers

Something like this will do the job:

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

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

+5
source

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 } 

Name it as follows:

 ./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 

It can 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 
+5
source
 TEXT=`grep value file | cut -f1` 
0
source

I think grep might be a better fit:

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

The ^ in the pattern matches the beginning of the line and ensures that you don't match the line where the value, not the key, was the right text.

0
source

All Articles