Created
May 8, 2016 11:45
-
-
Save taichunmin/d71518f27eb0fc8f13e9996658544924 to your computer and use it in GitHub Desktop.
在 Windows 系統上使用 regex 重新命名檔案
This file contains hidden or 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 | |
try { | |
$files = scandir('.'); | |
if(!is_array($files)) | |
throw new Exception('scandir error: '.var_export($files, true)); | |
foreach($files as &$file) | |
$file = iconv('cp950', 'utf-8//TRANSLIT', $file); | |
unset($file); | |
echo "Find What: "; | |
$find = '/'.stream_get_line(STDIN, 10000, PHP_EOL).'/us'; | |
echo "Replace With: "; | |
$replace = stream_get_line(STDIN, 10000, PHP_EOL); | |
$newFiles = array_combine(preg_grep($find, $files), preg_filter($find, $replace, $files)); | |
file_put_contents('rename.json', encode_json($newFiles)); | |
system('start rename.json'); | |
do { | |
echo 'Please Double Check "rename.json" and Enter Y to continue rename: '; | |
$input = stream_get_line(STDIN, 10000, PHP_EOL); | |
} while ($input !== 'Y' && $input !== 'y'); | |
$renames = json_decode(file_get_contents('rename.json'), true); | |
if(!is_array($renames)) | |
throw new Exception('parse "rename.json" faild.'); | |
foreach($renames as $oldfile => $newfile) { | |
$oldfile = iconv('UTF-8', 'cp950//TRANSLIT', $oldfile); | |
$newfile = iconv('UTF-8', 'cp950//TRANSLIT', $newfile); | |
if(false === rename($oldfile, $newfile)) | |
throw new Exception("rename $oldfile -> $newfile"); | |
} | |
} catch (Exception $e) { | |
echo 'error: '.$e->getMessage().PHP_EOL; | |
} | |
function encode_json($arr) { | |
return json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment