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

Re: Second Time Replace Regex

by robin (Chaplain)
on Dec 02, 2005 at 22:40 UTC ( #513740=note: print w/ replies, xml ) Need Help??


in reply to Second Time Replace Regex

If I understand your question correctly (which is far from guaranteed), you might try something like:

#!perl -pi~ my $p; my $done_replacement = 0; while (<>) { if (/^A (.*) B$/) { $p = $1; } elsif (defined $p && !$done-replacement) { s/^(C .*)$p$/$1 Q/; $done_replacement = 1; } }
Of course you must replace A, B, C and Q with your actual data, and pass the filename as a command-line argument to this script. It would be easier to give a precise answer if you could make your question more concrete by giving some example data. and saying what A, B and C really are.

I'm assuming that your A P B and C X P each constitutes an entire line of the file, because your use of “second line C X P” made me think that's what you meant.

Also, why is it important not to create an additional file? Usually it's safer to save the results of a transformation in a new file, in case something goes wrong. (In the code above, the switch -i~ causes the original file to be backed up with a name like oldname~, which gives you some protection at least.)


Comment on Re: Second Time Replace Regex
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://513740]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2015-07-08 00:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls