Moving files based on file name

T

Tor Rest

This is the scenario:

I have the following ZIP files in a directory. The numbers represent
versions (the highest number is the latest version of the file).
mercury001.zip
mercury002.zip
mercury003.zip
venus122.zip
venus123.zip
venus124.zip
mars005.zip
mars006.zip
mars007.zip

I wanted to keep the latest version and move (copy and delete) the rest to
an archive directory. The directory should only contain the following
files:
mercury003.zip
venus124.zip
mars007.zip

I am a novice PERL developer. How do I accomplish this? Would appreciate
some examples. Thanks!

Tor
 
G

Geraldo

Here is one way to do it.
Tested only on Active State perl v5.8.0 on Windows XP.
Will not work if the file order from a glob is not alphabetic.
Geraldo
---

#!/perl/bin/perl

use strict;
use Carp;

# path to zip files
my $zipDir = "C:/tmp/zips";
die ("$!") unless -d $zipDir;
# path to archive
my $archDir = "C:/tmp/arch";
die ("$!") unless -d $archDir;
# get the directory listing
#default order is by file name on NTFS
#may not be the case on other platforms
my @zips = glob $zipDir.'/*';
die ("$!") unless @zips;
# reverse it
#puts latest file name for each type first
@zips = reverse @zips;
my %types;
for ( @zips )
{
my $fn = $_;
# strip everything up to the filename
$fn =~ s/.*\///;
# put the file type into $1
$fn =~ s/(.*?)\d//;
if( $types{$1} )
{
# for loop has already hit the latest of this type
#archive the rest
$fn = $_;
$fn =~ s/.*\///;
rename $zipDir.'/'.$fn, $archDir.'/'.$fn || die;
}
# for loop has not hit this type yet
# set the type key to 1
$types{$1} = 1;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top