append field to file(nawk)

I have two files. File A and File B.

File A has two fields separated by comma

352020252365988, 652020100572356
546876543215667, 652065465654686
...

File B has many Fields separate by spaces

Date Name 352020252365988 Reference
Date2 Name2 546876543215667 Reference

I want to search for a match of Field 1 of file A in file 2. If there is a match print the line that contains the match, and append field 2 of File A at the end of each matched line.

so to have

Date

This code works for me

#!/bin/sh

while read line
do
  lookup=`echo "$line" | awk -vFS=',' '{print $1}'`
  field=`echo "$line" | awk -vFS=',' '{print $2}' | sed 's/^ //'`
  match=`grep "\<$lookup\>" file_b`
  if [ "$?" -eq "0" ]; then
    echo "$match" | while read record
    do
      echo "$record $field"
    done
  fi
done < file_a

assuming your files are named file_a and file_b.

The nested while is in case you have duplicate records and more than one record matches.

You'll need to redirect the output of this script to a file obviously.

Cheers
ZB

If the match is on the 3rd field of the 2nd file, then you can try this awk...

BEGIN {
   FS=","
   while(getline<xref) arr[$1]=$2
   FS=" "
}
$3 in arr {
   print $0, arr[$3] 
}

Use it like this...

awk -f above.awk -v xref=file_a file_b

Tested on the sample data...

Date Name 352020252365988 Reference 652020100572356
Date2 Name2 546876543215667 Reference 652065465654686

Thanx, both these scripts have worked!

I prefer the last one since I get to name files at the command prompt.

gurus u are, u guys!

___
Axl

Just FYI, if you change the code I posted thusly

#!/bin/sh

while read line
do
  lookup=`echo "$line" | awk -vFS=',' '{print $1}'`
  field=`echo "$line" | awk -vFS=',' '{print $2}' | sed 's/^ //'`
  match=`grep "\<$lookup\>" ${2}`
  if [ "$?" -eq "0" ]; then
    echo "$match" | while read record
    do
      echo "$record $field"
    done
  fi
done < ${1}

You can call this with ./my_script file_a file_b - i.e. specifying the files at the prompt as you wish!

Cheers
ZB