Re: compare 2 data files and extract fields for matched lines
- From: Jürgen Exner <jurgenex@xxxxxxxxxxx>
- Date: Thu, 27 Dec 2007 17:29:40 GMT
On shree <srigowrisn@xxxxxxxxxxx> wrote:
The best way to describe what I'm trying to do is through an example.
That helps somewhat.
I have 2 pipe delimited input files and want to extract a field from
file 2 and append it to file 1. Note I would like Output file to have
the same number of rows as Input File 1, with an additional field
whose value if present in file 2, should be inserted in this new
field. If its not present, then insert '0000'.
You forgot to mention and it is not clear from your example _which field_ is
the link between those 2 files.
Input File 1 (zipcode, city, state, county)
36003|Autaugaville|AL|AUTAUGA
36006|Billingsley|AL|AUTAUGA
..
..
Input File 2 (county, state, county population)
AUTAUGA|AL|49730
CROSS|AR|19056
MCPHERSON|KS|29380
..
Desired Output (zipcode, city, state, county, county population)
36003|Autaugaville|AL|AUTAUGA|49730
36006|Billingsley|AL|AUTAUGA|49730
72314|Birdeye|AR|CROSS|19056
---
I wrote the program below but it has logic error. Instead of getting
the above, I get the following.
Any guidance with fixing the code or perhaps a better way to do this
is really appreciated. The above is just a few lines from my real
[attempt with 2 arrays and nested loops snipped]
There is a much easier approach:
- read file 2 into a hash, using the link between the 2 files as the key and
the desired number as the value in each hash entry.
- then read file 1 line by line and if the key exists then write the line
with the hash value to the new file, otherwise write the line with 0000
appended to the new file.
Not only is this much easier to comprehend, it is also much faster with
O(n+m) instead of O(n*m).
jue
.
- References:
- Prev by Date: Re: compare 2 data files and extract fields for matched lines
- Next by Date: Re: reopen the file
- Previous by thread: Re: compare 2 data files and extract fields for matched lines
- Next by thread: Re: compare 2 data files and extract fields for matched lines
- Index(es):
Relevant Pages
|
|