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.)
-
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.
|