Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

What have you tried?

Not knowing which part has got you down, the quick break down is: open the input and output files, loop through them, change each line based on a regular expression that does what you want, print the changed line to the output file, and then close both file handles before exiting.

Most of this is taken care of if you use something like perl -pie 's/regexp/change/' filename. So the real problem is - what is the regular expression?

That depends on the spec. "As you can see" - I thought you just wanted to change "turkey" to "fox" until the last line - so it wasn't very obvious to me.

In your case, I would suggest code like this:

s/\S+(\s*)$/new-word$1/ if /elephant \* [/a-zA-Z]/
(the "last word" may not actually end the line - spaces after the last word doesn't change the fact it's the last word) The reason I didn't go with:
s/(elephant \* [/a-zA-Z].*?\s)\S+(\s*)$/$1new-word$2/
is because you don't always have more than one word following the *, and I couldn't think of a quick, easy, obvious way to do it in a single regex. Since everything is anchored, this shouldn't be much different in speed, but, more importantly, it should be correct.


In reply to Re: Changing the contents of a file by Tanktalus
in thread Changing the contents of a file by perlNinny

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (8)
As of 2024-03-28 07:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found