Xpx
Xpx

Reputation: 147

How to access files in subdirectories?

I have several subdirectories beneath in a main directory, and each subdirectory contains one or two text files. I need to copy these text files to another directory.

Here's how I coded. But it doesn't seem to work. What can I do? And is there a direct way of doing this?

#!/usr/bin/perl
use File::Copy;
my $directorypath;
opendir (DIR, '/d/work/abc') or die "cannot open path $!";
my @maindirectory = readdir (DIR);
closedir (DIR);

foreach my $subdirectorypath (@maindirectory)
{
    $subdirectorypath = join '', '/d/work/abc', $directorypath;
    chdir '$directorypath';
    my @textfile = glob "*.txt";
    foreach (@textfile)
    {
     $copiedfile = "/d/work/abcd/$_.txt."; #destination path 
     copy($_, $copiedfile) or die "File cannot be copied.";   
    }
}

Upvotes: 0

Views: 605

Answers (1)

Borodin
Borodin

Reputation: 126772

This is simple in a one-line Perl program

perl -MFile::Copy=copy -e'copy($_, "/d/work/abcd") for </d/work/abc/*/*.txt>'

Upvotes: 1

Related Questions