Advertisement
Guest User

Untitled

a guest
Jul 5th, 2015
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. <?php
  2.  
  3. $baseDir = $argv[1];
  4. if (false === is_dir($argv[1])) {
  5. die ("$baseDir is not a directory");
  6. }
  7.  
  8. // get all files with an extension
  9. $allFiles = array_filter(
  10. array_map('pathinfo', glob("$baseDir/*")),
  11. function($finfo) {
  12. return isset($finfo['extension']);
  13. }
  14. );
  15.  
  16. // init map of available numbers
  17. $newFiles = array_pad([], count($allFiles) + 1, null);
  18. unset($newFiles[0]);
  19.  
  20. // fill existing numbers
  21. foreach ($allFiles as $key => $file) {
  22. $index = $file['filename'];
  23. if (array_key_exists($index, $newFiles)) {
  24. unset($newFiles[$index], $allFiles[$key]);
  25. }
  26. }
  27.  
  28. // merge
  29. $newFiles = array_combine(array_keys($newFiles), $allFiles);
  30.  
  31. if (count($newFiles) === 0) {
  32. echo 'No files need to be renamed', PHP_EOL;
  33. exit;
  34. }
  35.  
  36. // rename
  37. foreach ($newFiles as $newNumber => $file) {
  38. $source = sprintf(
  39. '%s/%s',
  40. $file['dirname'],
  41. $file['basename']
  42. );
  43. $target = sprintf(
  44. '%s/%s.%s',
  45. $file['dirname'],
  46. $newNumber,
  47. $file['extension']
  48. );
  49. printf("Renaming %s to %s\n", $source, $target);
  50. copy($source, $target);
  51. unlink($source);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement