Renaming all files in the folder

2019-08-29 03:04发布

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

2条回答
神经病院院长
2楼-- · 2019-08-29 03:26

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();
}
查看更多
冷血范
3楼-- · 2019-08-29 03:42

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.

查看更多
登录 后发表回答