Quote:
Originally Posted by aritakum
... how to add this in the perl script, so I do not have to run a bash or command line script...
|
Suppose you have these text files in your directory that you want to process inside a
perl program:
Code:
$
$ cat a.txt
This is the first line in file a.txt
$
$ cat b.txt
This is the first line in file b.txt
This is the second line in file b.txt
$
$ cat c.txt
This is the first line in file c.txt
$
$
Here's one sample program:
Code:
$
$ cat process_files.pl
#!perl -w
# Script to process all *.txt files in current directory and put the output
# in the corresponding *.txt.new files in the current directory again.
my $indir = "."; # the input directory name
my $outdir = "."; # the output directory name
my $i = 0; # loop index
my $infile; # the input file name
my $outfile; # the output file name
while (defined($infile = glob($indir."\\*.txt"))) { # loop through the txt files in directory $indir
printf("(%d)\tNow processing file => %s\t",++$i,$infile);
$outfile = $outdir."\\".substr($infile,rindex($infile,"\\")+1).".new"; # name the output file
open (IFILE, "<$infile") or die "Can't open $infile: $!"; # open input file for reading
open (OFILE, ">$outfile") or die "Can't create file: $!"; # create output file for writing
while (<IFILE>) { # loop through contents of the input file
# now do all your processing here
# print to the output file
print OFILE "We've processed this line -> ".$_;
}
close(IFILE) or die "Can't close $infile: $!"; # close input file
close(OFILE) or die "Can't close $outfile: $!"; # close output file
printf("Output file => %s\n",$outfile);
}
$
$
I've used the Windows file separator since this is run on Windows + Cygwin. You may want to check the documentation for the functions like glob, print etc. You can set the input and output directories in this code; it was unnecessary to declare or use them here, since we are doing all processing in the current directory.
The execution is shown below:
Code:
$
$
$ perl process_files.pl
(1) Now processing file => .\a.txt Output file => .\a.txt.new
(2) Now processing file => .\b.txt Output file => .\b.txt.new
(3) Now processing file => .\c.txt Output file => .\c.txt.new
$
$ cat a.txt.new
We've processed this line -> This is the first line in file a.txt
$
$ cat b.txt.new
We've processed this line -> This is the first line in file b.txt
We've processed this line -> This is the second line in file b.txt
$
$ cat c.txt.new
We've processed this line -> This is the first line in file c.txt
$
$
Hope that helps,
tyler_durden