How to copy all the files of a particular type using Perl?
11,076
Solution 1
You can use the core File::Copy
module like this:
use File::Copy;
my @files = glob("$PATH1/*.txt");
for my $file (@files) {
copy($file, $ENV{DIRWORK}) or die "Copy failed: $!";
}
Solution 2
Using core File::Find and File::Copy and assuming you want all .txt
files in $PATH1
copied to $ENV{DIRWORK}
, and also assuming you want it to recurse...
use strict;
use warnings;
use File::Find;
use File::Copy;
die "ENV variable DIRWORK isn't set\n"
unless defined $ENV{DIRWORK} and length $ENV{DIRWORK};
die "DIRWORK $ENV{DIRWORK} is not a directory\n"
unless -d $ENV{DIRWORK};
my $PATH1 = q{/path/to/wherever};
die "PATH1 is not a directory" unless -d $PATH1;
find( sub{
# $_ is just the filename, "test.txt"
# $File::Find::name is the full "/path/to/the/file/test.txt".
return if $_ !~ /\.txt$/i;
my $dest = "$ENV{DIRWORK}/$_";
copy( $File::Find::name, $dest ) or do {
warn "Could not copy $File::Find::name, skipping\n";
return;
}
}, $PATH1 );
Give it a go ;)
Alternatively, why don't you use bash
?
$ ( find $PATH1 -type f -name '*.txt' | xargs -I{} cp {} $DIRWORK );
Author by
Lazer
Updated on June 04, 2022Comments
-
Lazer almost 2 years
Right now, I am using something like
copy catfile($PATH1, "instructions.txt"), catfile($ENV{'DIRWORK'});
individually for each of the
.txt
files that I want to copy. This code is portable as it does not use any OS specific commands.How can I copy all the text files from
$PATH1
toDIRWORK
, when I do not know the individual names of all the files, while keeping the code portable?