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|chennai

wants to replace that with

Capital of karnataka|is|bangalore

exp output

Capital of karnataka|is|bangalore

current 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
    quotemeta
    use warnings; use strict; my $old = quotemeta "welcome|to|chennai"; my $new = "Capital of karnataka|is|bangalore"; my $base = (); my @base = (); @base = <DATA>; chomp @base; foreach $base (@base) { if ( $base =~ /$old/ ) { $base =~ s/$old/$new/gi; print("Replaced!\n"); } print @base; } __DATA__ welcome|to|chennai

    The | is a special character in regexes (see perlre). It is used for alternation. The s///g modifier was replacing "welcome" with your $new string, then replacing "is" with your $new string, then replacing "chennai" with your $new string.

    I've also chomped your input.

      Hi, Thanks for your help.It worked.
Re: search and replace if pattern found in file
by ww (Archbishop) on Jul 31, 2014 at 14:33 UTC
    Please also note (and clarify) the disparity between your narrative description of the problem case and your sample IO data... which appears to be more nearly described (but still not accurately) as "surround verbs and/or prepositions with '|'s" or somesuch (frankly, I haven't expended any great effort on defining your problem case... but you should!).

    And ask yourself, do you need to do this so many times that a regex, rather than hand editing, is the answer. If so, maybe amend that to 'multiple regexen, applied sequentially.'

    Oh yes, also: enclose sample data in code tags, so we don't mis-read that data.

    See the instructions at the text-entry form which now exists at the bottom of a page showing your original node.


    check Ln42!

      Thanks for your feedback.I will follow the same on my future posts