perl - 使用通配符移动文件 [英] perl - moving files using wildcard
问题描述
是否可以使用 File::Copy
模块中的 perl 的 move
函数来使用通配符移动多个具有相同文件扩展名的常见文件?到目前为止,如果我明确命名文件,我只能让 move
工作.
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";
在我的 perl 程序结束时我想做什么,将所有这些名为 *.dat
的文件移动到一个存档目录.
What I want to do at the end of my perl program, move all these files named *.dat
to an archive directory.
推荐答案
你可以使用 Perl 的 glob
操作符来获取你需要打开的文件列表:
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:更好的方法是提供新目录而不是完整的新文件名.(抱歉没有早点想到这个!)
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
这篇关于perl - 使用通配符移动文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!