Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

problem with merging two files

Status
Not open for further replies.

agilo

Programmer
Feb 4, 2004
73
TR
Hi,

I am trying to merge two files based on the matching of the first column in both. The first file looks like:

x1 x2 x3 x4
name1 10 20 40
name2 30 20 15
name3 90 5 21

the second file looks like:

name1 xyz1
name1 xyz2
name2 xxx1
name2 yyy1
name2 zzz1

and I want the output to look like this:

name1 10 20 40 | xyz1
name1 10 20 40 | xyz2
name2 30 20 15 | xxx1
name2 30 20 15 | yyy1
name2 30 20 15 | zzz1

the problem is that the attached script does not show all lines, it shows only

name1 10 20 40 | xyz2
name2 30 20 15 | zzz1

The script I used is:

awk ' BEGIN {
{FS="\t"}
if (!fn) fn = "inp1.dat"
while ((getline<fn)>0) {
a[$1] = $1; b[$1] = $2 }
}
{ if (a[$1] == $1) printf "%s|%s\n",$0,b[$1] }
' inp2.dat

how can I show all lines in the form above, any help is appreciated.

 
Something like this ?
awk 'BEGIN {FS="\t"
if(!fn) fn="Name of first file"
while((getline<fn)>0){a[$1]=$1;b[$1]=$0}
}
$1==a[$1]{printf "%s|%s\n",b[$1],$2}
' NameOfSecondFile

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
nawk -f agilo.awk file2 file1

Code:
FNR == NR {
   a[$1]=$2
   next;
}

$1 in a {
  print $0, " | " , a[$1];
}

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Thanks very much for your quick reply,
The problem has been resolved..

 
I didn't know you had a problem.
I thought you were looking for a tip (as in tek-tip).

So.... what tip you ended up using AND what was the final solution?

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top