Saved has asked for the wisdom of the Perl Monks concerning the following question:

I wish to go thru a file and change every "<Any_text>" to "<New_txt>"
perl -lne 's/<.*>/<new text>/g && print'
changes first on the line, but not subsequent All help much appreciated, thanx

Replies are listed 'Best First'.
Re: Find/Chng every <any>
by stevieb (Canon) on Sep 03, 2010 at 19:46 UTC

    I hope I understand correctly what you are trying to do... does this seem right?

    # note the ? perl -ple 's/<.*?>/<blah>/g' data.txt

    Where data.txt contains:

    Hello. I'm <cold>. Very <cold>. I like to be <hot>. This is <today>. <today> I don't know what happened <yesterday>.

    ...and the result:

    perl -ple 's/<.*?>/<blah>/g' data.txt Hello. I'm <blah>. Very <blah>. I like to be <blah>. This is <blah>. <blah> I don't know what happened <blah>.

    Steve

      Thanx, that is great.
Re: Find/Chng every <any>
by moritz (Cardinal) on Sep 03, 2010 at 19:40 UTC
    if you have a string <a>b<c>, then the .* matches a>b<c, not just a. If you want avoid that, use [^<>]* instead of .*.

    See also: perlretut, perlre.

    Perl 6 - links to (nearly) everything that is Perl 6.

      It should be [^<>]+ not [^<>]* because * means 0 or more occurrence of previous character in regular expression of Perl.

        Unless, of course, "any text" can include an empty string.
Re: Find/Chng every <any>
by ambrus (Abbot) on Sep 05, 2010 at 07:41 UTC

    stevieb has already given a solution, but no-one has so far explained why your original code doesn't work. Why I think it doesn't work is this: the s///g expression returns false if it hasn't found any matches in the line, so then because of the && operator the print won't be ran. You could write this instead if you want all lines to be printed, even those where nothing is replaced:

    perl -lne 's/<.*>/<new text>/g; print'