Perl에서 디렉토리를 재귀 적으로 복사하고 파일 이름을 필터링하려면 어떻게해야합니까?
문제
Windows 시스템의 특정 Regex와 일치하는 파일 또는 디렉토리를 제외한 서브 디렉토리를 포함한 디렉토리를 어떻게 복사합니까?
해결책
나는 다음과 같은 일을 할 것입니다.
use File::Copy;
sub copy_recursively {
my ($from_dir, $to_dir, $regex) = @_;
opendir my($dh), $from_dir or die "Could not open dir '$from_dir': $!";
for my $entry (readdir $dh) {
next if $entry =~ /$regex/;
my $source = "$from_dir/$entry";
my $destination = "$to_dir/$entry";
if (-d $source) {
mkdir $destination or die "mkdir '$destination' failed: $!" if not -e $destination;
copy_recursively($source, $destination, $regex);
} else {
copy($source, $destination) or die "copy failed: $!";
}
}
closedir $dh;
return;
}
다른 팁
다른 옵션은 파일 :: xcopy입니다. 이름에서 알 수 있듯이 필터링 및 재귀 옵션을 포함하여 Windows Xcopy 명령을 더 많이 모방합니다.
문서에서 :
use File::Xcopy;
my $fx = new File::Xcopy;
$fx->from_dir("/from/dir");
$fx->to_dir("/to/dir");
$fx->fn_pat('(\.pl|\.txt)$'); # files with pl & txt extensions
$fx->param('s',1); # search recursively to sub dirs
$fx->param('verbose',1); # search recursively to sub dirs
$fx->param('log_file','/my/log/file.log');
my ($sr, $rr) = $fx->get_stat;
$fx->xcopy; # or
$fx->execute('copy');
# the same with short name
$fx->xcp("from_dir", "to_dir", "file_name_pattern");
유닉스와 같은 OS에 있고 액세스 할 수있는 경우 rsync (1)
, 당신은 그것을 사용해야합니다 (예 : system()
).
Perl의 파일 :: 사본은 약간 깨졌습니다 (예 : UNIX 시스템에서 권한을 복사하지 않음). 시스템 도구를 사용하지 않으려면 CPAN을보십시오. 아마도 파일 :: 복사 :: 재귀 사용될 수 있지만 옵션은 제외되지 않습니다. 다른 사람이 더 나은 아이디어를 갖기를 바랍니다.
사본으로 제외하는 방법을 모르겠지만 다음의 선을 따라 무언가를 작동시킬 수 있습니다.
ls -R1 | grep -v <regex to exclude> | awk '{printf("cp %s /destination/path",$1)}' | /bin/sh
고전적인 대답이 사용될 것입니다. 'cpio -p
':
(cd $SOURCE_DIR; find . -type f -print) |
perl -ne 'print unless m/<regex-goes-here>/' |
cpio -pd $TARGET_DIR
'cpio
'명령은 권한 보존을 포함하여 실제 복사를 처리합니다. '의 속임수'cd $SOURCE_DIR; find . ...
'이름에서 소스 경로의 주요 부분을 제거하는 것. 그 호출의 유일한 문제 'find
'Symlinks를 따르지 않는다는 것입니다. 추가해야합니다 '-follow
'그것이 당신이 원하는 것이라면.
제휴하지 않습니다 StackOverflow