It is currently Thu, 20 Jan 2022 10:08:42 GMT



 
Author Message
 Lookup and substituting a value..
If I have a file like:
XX 12345
YY abcde
ZZ xcvbn

and I have another file that is basically a lookup table:
12345 ttttt
43534 hhhhh
23443 jjjjj

and I want to look up the second columb in the first file, so '12345', and
find its match in the second file, and substitute the corresponding value
into the first file, so end up with:
XX ttttt
YY abcde
ZZ xcvbn

How the heck is that done?!



 Sun, 10 Sep 2006 08:21:30 GMT   
 Lookup and substituting a value..

Assuming the first file is named dat1 and the second file is dat2,

awk -v F1=dat1 '
BEGIN {
  while(getline < F1) {
    lookup[$1] = $2
  }

{
  lookup[$1] = $2

END {
  for(l in lookup)
  {
    printf("%s = %s\n", l, lookup[l])
  }

Output on my machine is

XX = ttttt
YY = abcde
ZZ = xcvbn

Joe
--
Don't worry, be happy
  - Bobby McFerrin



 Sun, 10 Sep 2006 08:58:11 GMT   
 Lookup and substituting a value..

With awk of course ;-):

awk 'NR == FNR {f1s[$2]=""; next}
        $1 in f1s { $1 = f1s[$1] }
        { print }' file1 file2

"join" might work too, take a look at it's man page.

Regards,

        Ed.



 Sun, 10 Sep 2006 11:14:14 GMT   
 Lookup and substituting a value..

<snip>

Oops:

awk 'NR == FNR {f1s[$2]=$1; next}
     $1 in f1s { $1 = f1s[$1] }
     { print }' file1 file2



 Sun, 10 Sep 2006 11:16:01 GMT   
 
   [ 4 post ] 

Similar Threads

1. Find numeric value in xml file, recalculate, and replace old value

2. Find numeric value in xml file, recalculate, and replace old value

3. ksh: finding the value of a value in a for loop

4. value of a value question...

5. settimeofday(2) succeeds for microsecond value more than USEC_PER_SEC and for negative value

6. MS Exchange Substitute

7. Script to substitute IP addresses

8. Script to substitute IP addresses

9. LDAp as substitute for NIS in solaris 2.6 and 7

10. substitute a word into a file


 
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group.
Designed by ST Software