search from file1 and replace into file2

I have 2 files:

file1.txt:

1|15|XXXXXX||9630716||0096000||30/04/2012|E|O|X||||20120525135617-30.04.2012|PAT66OLM|STA||||00001|STA_0096000_YYYPPPXTMEX00_20120525135617_02_P.pdf|
1|15|XXXXXX||9630252||0096000||30/04/2012|E|O|X||||20120525135617-30.04.2012|PAT66OLM|STA||||00001|STA_0096000_YYYPPPXTUSA00_20120525135617_03_P.pdf|
16|13|XXXXXX||9630954||0096000||30/04/2012|E|O|X||||20120525135617-30.04.2012|PAT66OLM|STA||||00002|STA_0096000_YYYPPPXTUSA00_20120525135617_03_P.pdf|
1|17|XXXXXX||9620613||0096000||30/04/2012|E|O|X||||20120525135617-30.04.2012|PAT66OLM|STA||||00001|STA_0096000_KKKLLLNT_20120525135617_01_P.pdf|

file2.txt:

0096000_9630716_PAT66OLM_P_20120525135617_000_D_00_0_en.pdf
0096000_9630252_PAT66OLM_P_20120525135617_000_D_00_0_en.pdf
0096000_9630954_PAT66OLM_P_20120525135617_000_D_00_0_en.pdf
0096000_9620613_PAT66OLM_E_20120525135617_000_D_00_0_en.pdf

I would like to do the following:

for each line in file2.txt; where "_" is the delimiter, 2nd record (9630716), search for this is string in file1.txt and then replace the entire string (filename in the last) viz (0096000_9630716_PAT66OLM_P_20120525135617_000_D_00_0_en.pdf) of file2.txt into file1.txt at the same position of file1.txt(STA_0096000_YYYPPPXTMEX00_20120525135617_02_P.pdf)

The final output should look like this.

file3.txt

1|15|XXXXXX||9630716||0096000||30/04/2012|E|O|X||||20120525135617-30.04.2012|PAT66OLM|STA||||00001|0096000_9630716_PAT66OLM_P_20120525135617_000_D_00_0_en.pdf|
1|15|XXXXXX||9630252||0096000||30/04/2012|E|O|X||||20120525135617-30.04.2012|PAT66OLM|STA||||0096000_9630252_PAT66OLM_P_20120525135617_000_D_00_0_en.pdf|
16|13|XXXXXX||9630954||0096000||30/04/2012|E|O|X||||20120525135617-30.04.2012|PAT66OLM|STA||||0096000_9630252_PAT66OLM_P_20120525135617_000_D_00_0_en.pdf|
1|17|XXXXXX||9620613||0096000||30/04/2012|E|O|X||||20120525135617-30.04.2012|PAT66OLM|STA||||00001|0096000_9620613_PAT66OLM_E_20120525135617_000_D_00_0_en.pdf|

I tried this but doesnt work.

while read each_ptf
do
search_str=`echo $each_ptf | awk -F"_" '{print $2}'`
sed -e 's/$search_str/$each_ptf/g' < file2.txt > file3.txt
done < file1.txt

Try:

awk 'NR==FNR{a[$2]=$0;next}$5 in a {$(NF-1)=a[$5]}1'  FS="_" file2.txt FS="|" OFS="|" file1.txt
1 Like

This works perfectly fine. Thanks a ton. !!! :b::b::b: