> I would like to find a word or character in a file and
> replace it with another word or character, while
> leaving others untouched. Currently, I am using the
> following method
>
> #!/bin/perl -Dr -w
> open(FILE,"$ARGV[0]") || die "Can't open $ARGV[0]:
> $!\n";
> open(FILE2,">$ARGV[0].spi") || die "Can't open
> $ARGV[0]_new: $!\n";
> while (<FILE>)
> {
> if (/(^VV\d+ )(TA)x(\d)x(.*)/)
> {
> print FILE2 $1,,$2,"[",$3,"]",$4,"\n";
> }
> else
> {
> print FILE2 $_;
> }
> }
> close FILE;
> close FILE2;
So you want to update FILE with the search and replace changes, right?
That means you either need a copy of the file in memory or you need to
rename the file that you create by writing to FILE2.
To rename the file:
use File::Copy qw(move);
# create backup of original file
move($ARGV[0],"$ARGV[0].bak");
# rename file you created
move("$ARGV[0].spi",$ARGV[0]);
To work with the file in memory:
OVERWRITES THE FILE YOU PASS AS A PARAMETER, SO MAKE SURE YOU HAVE A
BACKUP!
open FILE,$ARGV[0]
or die "couldn't open $ARGV[0]: $!\n";
my @file = <FILE>; close FILE;
foreach my $line (@file) {
$line =~ s/(^VV\d+ )(TA)x(\d)x(.*)$/$1$2\[$3\]$4/;
}
open FILE,">$ARGV[0]"
or die "couldn't open $ARGV[0] for write: $!\n";
print FILE join '',@file;
HTH,
-dave
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]