Fuv8
Fuv8

Reputation: 905

Move files in folders according to files and folders name

I have a list of files and a list of folders in which I would like to move the files.

In other words, I have files named like: a_myfile.txt and a folder named "a", then file: b_myfile.txt and a folder named "b", then c_myfile.txt and a folder named "c". I would like to move the file a_myfile.txt in the folder named "a", then the file named b_myfile.txt in the folder named "b" and so on. I have thousand of files and thousand of folders so it is impossible to move such files by hand.

Upvotes: 0

Views: 102

Answers (2)

Bill Wambua
Bill Wambua

Reputation: 91

I would have used the directory iterator class but some few PHP installations don't have SPL installed. So I'll just use a global solution.

Here is some code that will scan a directory and the file names, store them in an array then check the first characters before the underscore then move it accordingly.

    $directory = '/path/to/my/directory';
//to get rid of the dots that scandir() picks up in Linux environments
    $scanned_directory = array_diff(scandir($directory), array('..', '.'));

    foreach($scanned_directory as $filename)
    {
    $f = explode("_", $filename);
    $foldername = $f[0];

//Create directory if it does not exists
    if (!file_exists($foldername)) {
        @mkdir($foldername);
    }

//Move the file to the new directory
    rename($directory. "/". $filename, $directory. "/". $foldername. "/". $filename);


    }

Note: the new folders will be inside the old directory. You can customize it to create and move the new folders to a folder that you wish easily.

Upvotes: 0

devnull
devnull

Reputation: 123508

Using a loop, use shell parameter expansion to get the foldername, create it and move the file.

for i in *.txt; do
   mkdir -p "${i%%_*}"
   mv "${i}" "${i%%_*}"
done

Upvotes: 1

Related Questions