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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

comparing fields in files 2

Status
Not open for further replies.

cosmos77

Programmer
Oct 17, 2002
21
0
0
US
i have two text files.
one with one column of word like


File1:
--------
washington
jersey
texas

and then there is another file.

File2:
------

washington 34
Michigan 78
jersey 98
boston 876
texas 1078



i want the awkscript for searching the words from file1 in file2 and returns all lines that have the words and then print it to another file such that the file3 should contain

File3:
-------
washington 34
jersey 98
texas 1078


is there an awk script which can take care of this.


Thanks,
Ajay
 
Ajay:

In my opinion, awk is not the best tool to solve this problem.
You can do it in shell & grep:

#!/bin/ksh

rm -f file3
while read f1 f2
do
if grep "^$f1" file1 > /dev/null 2>&1
then
echo $f1" "$f2 >> file3
fi
done < file2

But if you insist:

#!/bin/ksh

# Solaris 7
awk ' BEGIN { i=1;
while ((getline < &quot;file1&quot;) > 0) { arr[i++] = $1 } }
{
# print the record if first field in array
for (ind in arr)
if($1 == arr[ind])
print $0

} ' file2 > file33

file1 is read into an awk array; Unfortunately, if extremely file1 is large
this, this might be prohibitive.

Regards,

Ed
 
If you don't mind the order of rows output then the join command could help. Such as:

#! /bin/sh
trap 'rm -f tmp1.$$ tmp2.$$ > /dev/null 2>&1' 0
trap &quot;exit 2&quot; 1 2 3 13 15
sort f1 > tmp1.$$
sort f2 > tmp2.$$
join -1 1 -2 1 -o 2.1 2.2 -t&quot; &quot; tmp1.$$ tmp2.$$ > f3

The trap commands remove the temp files and sorting is required for the join to work. Cheers,
ND [smile]

bigoldbulldog@hotmail.com
 
Or using awk

awk -f c.awk file2 > file3

# ------ c.awk ------
BEGIN {
while ((getline < &quot;file1&quot; > 0)) {
a[$0] = 1
}
}
{
if (a[$1]) print
}
CaKiwi
 
CaKiwi:

Good use of the associative array index properties. I should have picked up on that myself.

Nate:

Thanks for the join lesson. I have problem coming up where I can use this. Thanks!

Ed
 


Thanks for all the responses. But there is a problem

the awk script does not seem to list out all records.

Ajay
 
Please be more specific. Which records does it fail to print out? CaKiwi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top