Peter17
Peter17

Reputation: 3092

Renaming all files in the folder

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

Upvotes: 0

Views: 173

Answers (2)

Endoro
Endoro

Reputation: 37569

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.

Upvotes: 2

rojo
rojo

Reputation: 24466

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();
}

Upvotes: 1

Related Questions