Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $baseDir = $argv[1];
- if (false === is_dir($argv[1])) {
- die ("$baseDir is not a directory");
- }
- // get all files with an extension
- $allFiles = array_filter(
- array_map('pathinfo', glob("$baseDir/*")),
- function($finfo) {
- return isset($finfo['extension']);
- }
- );
- // init map of available numbers
- $newFiles = array_pad([], count($allFiles) + 1, null);
- unset($newFiles[0]);
- // fill existing numbers
- foreach ($allFiles as $key => $file) {
- $index = $file['filename'];
- if (array_key_exists($index, $newFiles)) {
- unset($newFiles[$index], $allFiles[$key]);
- }
- }
- // merge
- $newFiles = array_combine(array_keys($newFiles), $allFiles);
- if (count($newFiles) === 0) {
- echo 'No files need to be renamed', PHP_EOL;
- exit;
- }
- // rename
- foreach ($newFiles as $newNumber => $file) {
- $source = sprintf(
- '%s/%s',
- $file['dirname'],
- $file['basename']
- );
- $target = sprintf(
- '%s/%s.%s',
- $file['dirname'],
- $newNumber,
- $file['extension']
- );
- printf("Renaming %s to %s\n", $source, $target);
- copy($source, $target);
- unlink($source);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement