Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Find/Chng every <any>

by Saved (Beadle)
on Sep 03, 2010 at 19:36 UTC ( [id://858794]=perlquestion: print w/replies, xml ) Need Help??

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'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://858794]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2024-03-29 14:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found