Created
June 7, 2015 10:09
-
-
Save gooh/c8e00b99ef02a6eca602 to your computer and use it in GitHub Desktop.
Renames all files in a folder having an extension to a sequential numeric name preserving existing numerically named file names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment