unkaitha
unkaitha

Reputation: 225

Moving files into different folders/directories based on their name

I have a directory or folder consisting of hundreds of files. They are named and arranged alphabatically. I want to move the files into directories or folders according to the first character of their name (i.e. files starting with a into one folder, files starting with r into another folder, etc).

Is there a way to do it without using CPAN modules?

Upvotes: 3

Views: 15444

Answers (2)

hmmm
hmmm

Reputation: 1

Use glob(), or the built-in File::Find to build a list of files for each starting letter.

Upvotes: 0

David W.
David W.

Reputation: 107090

Are the files all in that one folder, or are they in subfolders? If they are all in a single folder, you can use opendir to access the directory, and then readdir to read the file names and copy them elsewhere (using File::Copy module's move or copy function.

use strict;
use warnings;
use autodie;
use File::Copy;   #Gives you access to the "move" command

use constant {
    FROM_DIR => "the.directory.you.want.to.read",
    TO_DIR   => "the.directory.you want.to.move.the.files.to",
};

#Opens FROM_DIR, ao I can read from it
opendir my $dir, FROM_DIR;

# Loopa through the directory
while (my $file = readdir $dir) {
    next if ($file eq "." or $file eq "..");
    my $from = FROM_DIR . "/" . "$file";
    move $from, TO_DIR;
}

This doesn't do exactly what you want, but it should give you the idea. Basically, I'm using opendir and readdir to read the files in the directory and I'm using move to move them to another directory.

I used the File::Copy module, but this is included in all Perl distributions, so it's not a CPAN module that must be installed.

Upvotes: 9

Related Questions