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; }
In reply to Replace value in the text file by mhoang
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |