Search code examples
batch-fileoverwritebatch-rename

Rename files within subfolder and overwrite via batch


Here's the current code:

@ECHO OFF

ECHO.
REM rename 
REN "H:\DIRECTORY with Space\folder1\*.*" "H:\DIRECTORY with Space\Folder1\TEST_*.*"

ECHO.
DIR nofile || (PAUSE && EXIT /B 1)

I have also tried with move / y

move /y "H:\DIRECTORY with Space\folder1\*.*" "H:\DIRECTORY with Space\folder1\TEST_*.*"

Both wont work (syntax error or directory not found). Basically trying to rename everything within a sub-folder with a prefix ("Test_") and overwrite any duplicates.


Solution

  • Give this a try. I have commented the code to help better explain how it works.

    @ECHO OFF
    
    :: Changes to a directory and saves previous directory to go back to
    PUSHD "H:\DIRECTORY with Space\folder1\"
    
    :: Critical that you USE this instead of a normal FOR command.
    :: A normal FOR command may attempt to rename a file twice.
    FOR /F "delims=" %%G IN ('DIR /a-d /b *.*') do rename "%%~G" "TEST_%%~G"
    
    :: Goes back to the previous directory.
    POPD