使用目录名称重命名文件

Rename files with its directory name

我有一些目录包含如下文件:

folder1/filename.jpg
folder2/filename.pdf
folder3/filename.jpg

我想用相应的目录名称重命名所有目录中的所有文件(但保留其扩展名),例如:

folder1/filename.jpg to folder1/folder1.jpg
folder2/filename.pdf to folder2/folder2.pdf
folder3/filename.jpg to folder3/folder3.jpg

编辑:另外,我想将所有重命名的文件复制到另一个目录(如 "allfiles")。

我找到了a similar question in Perl language

如何使用 PHP 实现它?

这里有一个方法可以做到这一点:

<?php

// Array with all subdirectories in directory
$dirArray = array_filter(glob('/path/to/directory/*'), 'is_dir');

// $dir is the path to the subdirectory
foreach ($dirArray as $dir) {

    // $dirName has the future name of files in that subdirectory
    $dirName = basename($dir);

    // Take all the elements in the subdirectory (except '.' and '..')
    $filesArray = array_diff(scandir($dir), array('.', '..'));

    $i = 0;
    foreach ($filesArray as $file) {
        // Take the file extension for the rename method
        $fileExtension = pathinfo($file, PATHINFO_EXTENSION);

        $oldName = $dir . "/" . $file;
        $newName = $dir . "/" . $dirName . "-" . $i . "." . $fileExtension;

        rename($oldName, $newName);
        $i++;
    }
}

如果您确定每个子目录中只有一个文件,您可以使用此行 $newName:

$newName = $dir . "/" . $dirName . "." . $fileExtension;