I'm totally new to Perl, and I need to get a small find and replace done to change the date format in a set of l开发者_StackOverflow社区arge file. The files have dates in the format: dd.mm.yyyy and I need to change them to: mm-dd-yyyy
How do I do this with perl?
I have a basic code to read through the files in a directory and write to an output file, I'll need to have my replace logic in-between the while loop (if i'm not wrong!).
#!c:/perl64/bin/perl.exe
#loop around a directory
@files = <C:/perl64/data/*>;
# loop around files
foreach $file (@files) {
#Read File
open READ, $file or die "Cannot open $read for read :$!";
#Output File
$fname=substr($file, rindex($file,"/")+1,length($file)-rindex($file,"/")-1);
$write="C:/perl64/output/$fname";
open WRITE, ">$write" or die "Cannot open $write for write :$!";
#Loop Around file
while (<READ>) {
# TO DO: Change date format from dd.mm.yyyy to mm-dd-yyyy
#Write to ourput file
print WRITE "$_";
}
}
Regards,
Anand
You can use the substitution operator s///
:
while (<READ>) {
s/(\d{2})\.(\d{2})\.(\d{4})/$2-$1-$3/;
print WRITE "$_";
}
Here's a simple script that will take optional arguments for input and output directories.
The use of opendir
instead of a glob will save you some trouble cleaning up the file names.
use strict;
use warnings;
use autodie;
my $indir = shift || "C:/perl64/data";
my $outdir = shift || "C:/perl64/output";
opendir(my $in, $indir);
while (readdir $in) {
next unless -f;
open my $infile, '<', $_;
open my $outfile, '>', $outdir . "/" . $_;
while (<$infile>) {
s/([0-9]{2})\.([0-9]{2})\.([0-9]{4})/$2-$1-$3/g;
print $outfile $_;
}
}
精彩评论