myfrndjk has asked for the wisdom of the Perl Monks concerning the following question:
Hi I am here to seek a help from you.I want to search and replace the particular line from text file.The issue is my text file contains "|" between each sentence.When i try to replace the line it ends up printing 3 times instead of 1 time.Thanks
use strict; use warnings; my $old="welcome|to|chennai"; my $new="Capital of karnataka|is|bangalore"; my $base = (); my @base = (); my $file="c:/users/jeyakuma/desktop/search.txt"; open(BASE, $file) || die("Could not open file!"); @base=<BASE>; close (BASE); foreach $base(@base) { if($base =~ /$old/){ $base =~ s/$old/$new/gi; print ("Replaced!\n"); } open (BASE, ">$file"); print BASE @base; close (BASE); };
input file contains
welcome|to|chennaiwants to replace that with
Capital of karnataka|is|bangaloreexp output
Capital of karnataka|is|bangalorecurrent result
Capital of karnataka|is|bangalore|Capital of karnataka|is|bangalore|Capital of karnataka|is|bangalore
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: search and replace if pattern found in file
by toolic (Bishop) on Jul 31, 2014 at 14:06 UTC | |
by myfrndjk (Sexton) on Jul 31, 2014 at 14:29 UTC | |
|
Re: search and replace if pattern found in file
by ww (Archbishop) on Jul 31, 2014 at 14:33 UTC | |
by myfrndjk (Sexton) on Aug 01, 2014 at 19:27 UTC |