Renaming all files in the folder

痴心易碎 提交于 2019-12-25 07:27:29

问题


How to rename all files in the folder using Windows batch? Basically, the part of the name starting from _Done should be removed:

some_file_name_Done_34534576456.CSV -> some_file_name.CSV some_other_file_name_Done_23232343.CSV -> some_other_file_name.CSV


回答1:


Try this, solution in Batch:

@echo off &setlocal enabledelayedexpansion
FOR %%i in (*.*) do call:process "%%~i"
GOTO :eof

:process
set "fname=%~n1"
set "tname=%fname:*_Done=%"
if "%fname%"=="%tname%" echo %~1: nothing to do&goto :eof
set "fname=!fname:_Done%tname%=!%~x1"
if exist "%fname%" echo %fname%: already exists&goto :eof
ren "%~1" "%fname%"
goto :eof

endlocal

Edit: changed some ! to % for clarification. This doesn't change the effect.




回答2:


If you don't mind using another language, you can rename with regular expressions. Here's what you asked for in JScript. Save this as something.js, put it in the directory containing your CSV files, and run it with cscript /nologo something.js.

var fso = new ActiveXObject("Scripting.FileSystemObject");
var folder = fso.GetFolder(".");

var files = new Enumerator(folder.Files);

while (!files.atEnd()) {
    var file = '' + files.item();
    if (/\.csv$/i.test(file)) {
        var dest = file.replace(/_Done[^\.]+/i, '');
        if (dest != file) {
            WSH.Echo('Renaming ' + file + ' -> ' + dest);
            files.item().Move(dest);
        }
    }
    files.moveNext();
}


来源:https://stackoverflow.com/questions/15523995/renaming-all-files-in-the-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!