Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl - moving files using wildcard

Tags:

perl

Is it possible to use perl's move function from File::Copy module to use a wildcard to move a number of common files with the same file extension? So far, I can only get move to work if I explicitly name the files.

For example, I wanted to do something like so:

my $old_loc = "/share/cust/abc/*.dat";
my $arc_dir = "/share/archive_dir/";

Right now, I can do one file like so:

use strict;
use warnings;
use File::Copy;

my $old_loc = "/share/cust/abc/Mail_2011-10-17.dat";
my $arc_dir = "/share/archive_dir/Mail_2011-10-17.dat";
my $new_loc = $arc_dir;

#archive
print "Moving files to archive...\n";
move ($old_loc, $new_loc) || die "cound not move $old_loc to $new_loc: $!\n";

What I want to do at the end of my perl program, move all these files named *.dat to an archive directory.

like image 241
jdamae Avatar asked Oct 24 '11 21:10

jdamae


2 Answers

You can use Perl's glob operator to get the list of files you need to open:

use strict;
use warnings;
use File::Copy;

my @old_files = glob "/share/cust/abc/*.dat";
my $arc_dir = "/share/archive_dir/";

foreach my $old_file (@old_files)
{
    my ($short_file_name) = $old_file =~ m~/(.*?\.dat)$~;
    my $new_file = $arc_dir . $short_file_name;

    move($old_file, $new_file) or die "Could not move $old_file to $new_file: $!\n";
}

This has the benefit of not relying on a system call, which is unportable, system-dependent, and possibly dangerous.


EDIT: A better way to do this is just to supply the new directory instead of the full new filename. (Sorry for not thinking of this earlier!)

    move($old_file, $arc_dir) or die "Could not move $old_file to $new_file: $!\n";
    # Probably a good idea to make sure $arc_dir ends with a '/' character, just in case
like image 165
Platinum Azure Avatar answered Sep 18 '22 05:09

Platinum Azure


From the File::Copy documentation:

If the destination already exists and is a directory, and the source is not a directory, then the source file will be renamed into the directory specified by the destination.

use strict;
use warnings;
use File::Copy;

my $old_loc = "/share/cust/abc/*.dat";
my $arc_dir = "/share/archive_dir/";

for my $file (glob $old_loc) {
    move ($file, $arc_dir) or die $!;
}
like image 42
TLP Avatar answered Sep 19 '22 05:09

TLP