Moving files based on file name

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tor Rest

    Moving files based on file name

    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


  • Geraldo

    #2
    Re: Moving files based on file name

    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;
    }

    Comment

    Working...