Skip to content

Instantly share code, notes, and snippets.

@gooh
Created June 7, 2015 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gooh/c8e00b99ef02a6eca602 to your computer and use it in GitHub Desktop.
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
<?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