B
Bart Van der Donck
gjena1 said:I'm new to perl. Would someone please give me an example
of a perl program to read from a fileA which has several
datas, and search fileA for string1 and change it to string2
in fileA. string1 is located in various places in each
line. Find the the string1 that is located 10 spaces from
the beginning of each line in fileA.
Any suggestions would be greatly greatly appreciated.
This could be an example. Your input file must be readable ($fileA)
and your output file must be writable ($fileB). Script changes only
the first $string1 per line that is exact after 10 spaces from the
beginning. If you're on Windows then you will probably need to change
#!/usr/bin/perl to Perl's path on your machine.
-------------------------------------
PROGRAM START
-------------------------------------
#!/usr/bin/perl
use strict;
use warnings;
# init
my $fileA = "initialfile.txt";
my $fileB = "alteredfile.txt";
my $string1 = "XXXX";
my $string2 = "YYYY";
my $tenspaces;
my @initialfile;
my @alteredfile;
my $alteredline;
for (1..10) {$tenspaces.=' '}
# read $fileA and do regexp in each line
open (R, "$fileA")||die"$!";
# following code line doesn't always work on Win OS
# I 'ld suggest to uncomment when on unix:
# flock(W,1) || die "Cant get LOCK_SH on file: $!";
while (<R>)
{
push @initialfile, $_;
$alteredline=$_;
$alteredline=~s/^ {10}$string1/$tenspaces$string2/;
push @alteredfile, $alteredline;
}
close R;
# write new content to $fileB
open (W, ">$fileB")||die "$!";
# following code line doesn't always work on Win OS
# I 'ld suggest to uncomment when on unix:
# flock(W,1) || die "Cant get LOCK_SH on file: $!";
print W @alteredfile;
close W;
# small report utility to screen
print "\n------------------\n";
print "Initial file:";
print "\n------------------\n";
print @initialfile;
print "\n------------------\n";
print "Altered file:";
print "\n------------------\n";
print @alteredfile;