Home > Archive > PERL Beginners > February 2005 > Appending in between some file
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Appending in between some file
|
|
| Anish Kumar K. 2005-02-25, 8:56 am |
| Hi
I wanted to append some line in between a text file. So what I tried is with the s command I tried moving the pointer and then do appeding, but for some reason it was not getting appended.
I know there are ways to make this task possible. I am afraid abot the memory consumption so I haven;t used it.
Say I have a text file
Java
Oracle
Visual basic
I wanted to insert PERL after Oracle...So now the file should be
Java
Oracle
PERL
Visual basic
I did with array. ie first copying the file into array and then doing.
is there any alternate way
Anish
| |
| Thomas Bätzler 2005-02-25, 8:56 am |
| Anish Kumar K. <anish@vitalect-india.com> asked:
> I wanted to append some line in between a text file. So what
> I tried is with the s command I tried moving the pointer
> and then do appeding, but for some reason it was not getting
> appended.
When you s () and write in the middle of a file, it'll
overwrite what's already there.
> Say I have a text file
>
> Java
> Oracle
> Visual basic
>
> I wanted to insert PERL after Oracle...So now the file should be
>
> Java
> Oracle
> PERL
> Visual basic
>
> I did with array. ie first copying the file into array and then doing.
>
> is there any alternate way
First, there is an alternate spelling - the language is Perl,
and perl(.exe) is its interpreter.
The way it's done is thus:
use File::Copy;
rename( $filename, "$filename.tmp" ) or die "rename failed: $!";
open( IN, "$filename.tmp" ) or die "open failed: $!";
open( OUT, ">$filename" ) or die "open failed: $!";
while( <IN> ){
print OUT;
if( m/^Oracle/ ){
print OUT "Perl\n";
copy( *IN, *OUT );
# or just: print OUT while <IN>;
}
}
HTH,
Thomas
| |
| John W. Krahn 2005-02-25, 8:55 pm |
| Anish Kumar K. wrote:
> Hi
Hello,
> I wanted to append some line in between a text file. So what I tried is
> with the s command I tried moving the pointer and then do appeding,
> but for some reason it was not getting appended.
>
> I know there are ways to make this task possible. I am afraid abot the
> memory consumption so I haven;t used it.
>
> Say I have a text file
>
> Java
> Oracle
> Visual basic
>
> I wanted to insert PERL after Oracle...So now the file should be
>
> Java
> Oracle
> PERL
> Visual basic
>
> I did with array. ie first copying the file into array and then doing.
>
> is there any alternate way
As explained in the FAQ:
perldoc -q "insert a line in the middle of a file"
use Tie::File;
tie my @array, 'Tie::File', 'filename' or die "Cannot open 'filename' $!";
splice @array, 2, 0, 'Perl';
untie @array;
John
--
use Perl;
program
fulfillment
|
|
|
|
|