mhoang has asked for the wisdom of the Perl Monks concerning the following question:
Hello guys, I have two text files: file1.txt
file2.txt"A123","valueA1","valueB1" "B234","valueA2","valueB2" "C345","valueA3","valueB3" "D456","valueA4","valueB4" "E567","valueA5","valueB5" "F678","valueA6","valueB6"
I want to replace the value in file 1 with the second column value in file 2 if the key is matched."C345","valueX1","valueY1" "D456","valueX2","valueY2"
and here is my code, but I actually don't know how to write back to file1 with new value. Pls shed some light into it thanks."A123","valueA1","valueB1" "B234","valueA2","valueB2" "C345","valueX1","valueB3" "D456","valueX2","valueB4" "E567","valueA5","valueB5" "F678","valueA6","valueB6"
#!/usr/bin/perl #use strict; #use warnings; open fh1,"<C:/Perl-Script/file1.txt"; open fh2,"<C:/Perl-Script/file2.txt"; open fh3,">>C:/Perl-Script/file3.txt"; @a=<fh1>; @b=<fh2>; foreach $b(@b) { @k = split ' ', $b; $hash2{$k[0]} = $k[1]; } foreach $a(@a) { @k = split ' ', $a; $hash1{$k[0]} = $k[1]; } while(($k,$v)= each %hash1) {$hash1{$k} = $hash2{$k} if (exists $hash2{$k})}; foreach $value (@a) { print fh1 $value; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Replace value in the text file
by huck (Prior) on Jun 28, 2017 at 05:54 UTC | |
by Anonymous Monk on Jun 28, 2017 at 06:48 UTC | |
|
Re: Replace value in the text file
by Marshall (Canon) on Jun 28, 2017 at 07:13 UTC | |
|
Re: Replace value in the text file
by tybalt89 (Monsignor) on Jun 28, 2017 at 17:29 UTC | |
|
Re: Replace value in the text file
by mhoang (Acolyte) on Jun 28, 2017 at 23:46 UTC | |
by afoken (Chancellor) on Jun 29, 2017 at 04:25 UTC | |
by haukex (Archbishop) on Jun 29, 2017 at 07:43 UTC | |
by afoken (Chancellor) on Jun 30, 2017 at 21:04 UTC | |
by mhoang (Acolyte) on Jun 30, 2017 at 05:43 UTC | |
by AnomalousMonk (Archbishop) on Jun 30, 2017 at 06:19 UTC | |
| |
by haukex (Archbishop) on Jun 30, 2017 at 08:59 UTC | |
| |
by mhoang (Acolyte) on Jun 30, 2017 at 02:53 UTC |