in reply to Re: Inserting a line in the middle of a text
in thread Inserting a line in the middle of a text
That seems like a contortion to avoid opening an input filehandle and a separate output filehandle.
use strict; use warnings; my $filename = "inputfile.txt"; my $outputfile = $filename . "out"; my( $infh, $outfh ); open( $infh, '<', $filename ) or die $!; open( $outfh, '>', $outputfile ) or die $!; while( my $line = <$infh> ) { if( $line =~ /\bWilliam\b/i ) { print $outfh "Nick\n"; } print $line; } close $infh or die $!; close $outfh or die $!; rename $outputfile, $filename or die $!;
This is pretty close to what the -i commandline switch does for Perl one liners, with the exception of the "-i.bak" behavior, which could easily be implemented here too.
This whole thing could be written as a one liner, by the way:
perl -pi.bak -e "/\bWilliam\b/i && print qq/Nick\n/;" filename.txtObviously I forgot the names you're searching on, but the principle works.
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Inserting a line in the middle of a text
by ikegami (Patriarch) on Jan 20, 2009 at 17:34 UTC |