Matt,
Thanks for your detailed answer. One question though: I am not looking to
replace line 3 but to "insert" additional text starting from line 3. e.g.:
textfile before:
******************************
RELEASE NOTES
******************************
Feature 1: blah blah blah
blah blah blah
blah blah blah
textfile after:
******************************
RELEASE NOTES
******************************
Feature 2: xxx xxx xxx
xxx xxx xxx
Feature 1: blah blah blah
blah blah blah
blah blah blah
I am doing so from within a script and using a file handle.
Will your suggestion still work?
Thanks a lot,
Shy Aviram
Texas Instruments
-----Original Message-----
From: Shaw, Matthew [mailto:[EMAIL PROTECTED]
Sent: Wednesday, May 05, 2004 4:23 PM
To: Aviram, Shy
Subject: RE: How do I append text to a text file - in the 3rd row ?
This one-line will work for the problem you describe. I'm not sure what
context you're looking to use this in, so I'll explain each step further
below:
perl -pi.bak -we's/\z/Your new line\n/ if $. == 2;' your_text_file.txt
I'll break it down for you:
The -p option cause perl to assume a loop around your file which allows
you to perform some processing (via the $_ default variable) and then
print the results. Compare with the -n option. Described in: perldoc
perlrun
The -i option (with the option .bak argument) causes perl to 'edit the
file in place' and optionally save a backup of the file with the
extension .bak. Described in: perldoc perlrun
-w turns on warnings. (perldoc perlrun)
-e is the script you want to execute. (perldoc perlrun)
The script is one line:
s/\z/Your new line\n/ if $. == 2;
This regex search & replace matches end of string (beyond the newline)
and replaces it with a new, newline terminated line. (Thus 'inserting' a
new line to the file). It is followed by an 'if' statement that compares
the value of $. (the line number variable) against 2 thus only
performing the match if on line 2. (perldoc perlre, perldoc perlretut,
perldoc perlvar, perldoc perlsyn)
>From within a program, you could apply the same logic by opening a file
and using the regex against it. $. Will contain the 'current' line
number from the most recently accessed file handle. Note that there are
some caveats to this which can be found in perldoc perlvar.
Hope this helps.
Matt Shaw
xwave, An Aliant Company
Desk: 506-389-4641
Cell: 506-863-8949
[EMAIL PROTECTED]
> -----Original Message-----
> From: Aviram, Shy [mailto:[EMAIL PROTECTED]
> Sent: Wednesday, May 05, 2004 8:25 AM
> To: [EMAIL PROTECTED]
> Subject: How do I append text to a text file - in the 3rd row ?
>
> Hi,
>
> I have a text file I open and want to add new text into. However, I
want
> the
> new text to be at the 3rd row of the file (below the headline) and not
at
> the end.
>
> Thanks,
>
> Shy
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>