Skip to content

Instantly share code, notes, and snippets.

@mmenavas
Created May 19, 2014 16:19
Show Gist options
  • Save mmenavas/ee58d14c89155d2a8ce2 to your computer and use it in GitHub Desktop.
Save mmenavas/ee58d14c89155d2a8ce2 to your computer and use it in GitHub Desktop.
CLI PHP script to non-recursively rename files
<?php
/**
* Script to non-recursevly rename files in the directory where the script is.
* TODO:
* - Provide help flag (option -h or -help)
* - Check special characters
*/
// Search and replace parameters
$search = $replace = "";
if ($argv[1]) {
$search = $argv[1];
if ($argv[2]) {
$replace = $argv[2];
}
}
else {
echo "Provide search and replace parameters. For example 'php rename.php new-name old-name";
exit;
}
// Path to current directory
$path = dirname(__FILE__);
// Iterator object
$dir = new DirectoryIterator($path);
foreach ($dir as $file) {
// Reset success flag
$success = false;
// Do not rename dot-leading files and the script itself
if (!$file->isDot() && ($file->getFilename() != "rename.php")) {
// Get new name
$new_name = str_replace($search, $replace, $file->getFilename());
// Check if match is found
if ($new_name != "" && $new_name !== $file->getFilename()) {
// On success, set flag to true
$success = copy("{$path}/{$file->getFilename()}", "{$path}/{$new_name}");
if ($success) {
echo "Renamed {$file->getFilename()} to $new_name\n";
unlink("{$path}/{$file->getFilename()}");
}
} // End match check
} // End name check
} // End loop
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment