Please find code as below. I'm a bit of a noob, so it should all either be easy enough or commented. RSVP if there's anything needs explanation.
#!usr/bin/perl -w-T
#ABOUT
# Objective: renames all .csv files (from MS Excel) in a given
#directory to <StationNumber><Parameter>.csv where <StationNumber> and
#<Parameter> are taken from the file contents.
#DETAIL
# Abstracts relevant information from a file, re-names the file to
#(typically):
#<GaugeRefNo>REev.csv for tipping-bucket rainfall gauges.
#<GaugeRefNo>RSst.csv for storage rainfall gauges.
#CODE
use strict;
use diagnostics;
use Cwd;
my %renamefiles=();
my $renamefiles;
my @keys=();
my $key;
{
my $files;
my @files=<c:/Storage/*.csv>; #Reads all csv files
foreach(@files)
{ my $open=$_; #Read current file to process from array
my $string; #Slurp file line by line
my $gaugeref;
my $gaugeparam;
my $currentdir;
my $newdir;
my $chaff;
my $result;
my $newname;
my $oldname;
######TODO - Read $param from file contents
# my $param="REev"; #For tipping bucket raingauges
my $param="RSst"; #For storage raingauges
# my $param="SG"; #For stage (level)
######
my $extension="csv";
#Strip filename to "/" in path
$newdir=$_;$chaff=chop($newdir) while substr($newdir,length($n
+ewdir)-1)!~/\//;
chdir $newdir;
#PARSE IN
open(INFILE,"<", $open) or die "Couldn't open $open $!";
print "Opened $open \n";
while(<INFILE>) #Loop through lines
{ $string=$_;
# GET STATION NUMBER
if (lc($string)=~ /(gauge ref|station number)/)
{ my $station=$string;
chomp $station;
$chaff=chop($station) while substr($station,le
+ngth($station)-1)=~/\D/; #drop chaff
$result.=chop($station) while substr($station,
+length($station)-1)=~/\d/; #append hits
$gaugeref=reverse($result);
next;
};
};
close $open;
$result="";#Clear
$result.=chop($open) while substr($open,length($open)-1)!~/\//
+;#read filename from path until encounters /
$oldname=reverse($result);
$newname="$gaugeref$param.$extension";
print "Old:$oldname\nNew: $newname\n";
%renamefiles=($oldname=>$newname);
@keys=sort keys %renamefiles;
foreach $key(sort keys %renamefiles)
{
if (!(-w $oldname))
{print "$oldname is not writeable\n";}
else{
use Stat::lsMode;
my $mode = file_mode($oldname);
print "Filemode is $mode\n";
renamefile("$key","$renamefiles{$key}");
};
};
};
};
######SUBS######
sub renamefile{
my $oldname=shift;
my $newname=shift;
my $success="";
print qq{Attempting to rename $oldname to $newname\n};
$success=rename $oldname, $newname;
if ($success){print "Changed $oldname to $newname\n"}
else
{print "Failed to rename $oldname to $newname $!\n";exit};
};
Thanks in for any help. |