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

AWK: Update data in one file while looking into secod file....

Status
Not open for further replies.

goyalpdm

Programmer
Jan 11, 2003
42
US
Hi,

Please see if someone can help me on this:

I have two files:
- file_1 (col_11, col_12) and
- file_2 (col_21, col_22, col_23 ...)

Of these, file_1 is master file and is used to update data in file_2.

How to update? Read first column of file_2 (col_21) and compare it with second column of file_1 (col_12). If the two match, update first column of file_2 (col_21) with first column of file_1 (col_11).

Exception: If no matching data is found, leave the record as is AND if multiple matching records are found, use first available match.

Thanks,
Sachin
 
A starting point:
nawk '
NR==FNR{if(!($2 in a))a[$2]=$1;next}
{if($1 in a)$1=a[$1];print}
' file_1 file_2 > newfile_2

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
I tried this in the command prompt.

It generated newfile_2 BUT exactly same as file_2. As I said, I like to update first column of file_2 with second column of file_1.
 
What is the column separator ?

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Pipe "|"... Guess, I should have mentioned it in first place.
 
nawk '
BEGIN{FS=OFS="|"}
NR==FNR{if(!($2 in a))a[$2]=$1;next}
{if($1 in a)$1=a[$1];print}
' file_1 file_2 > newfile_2

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Is it possible to avoid newfile_2? Ofcourse I can mv newfile_2 file_2 but it would be much cleaner if can avoid newfile_2 and update file_2.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top