Search code examples
windowsbatch-filebatch-rename

How to rename files in subfolder into a specific format


I have files named as RabcdYYMMKKACCOUNT.TXT in the Subfolders of a folder where YYMM is year, month this will change. KK is another identifier, I want all the files to be renamed to MSFKKDNB.ABC, the KK is the identifier in the input file.

Below is the one i tried and the result of it:

FOR /R %%f IN (*account.txt) DO REN "%%f" *dnb.abc

R00531706AUAccount.txt is renamed to R00531706AUAccount.txtdnb.abc

but the output should be MSFAUDNB.abc


Solution

  • This could be done for example with:

    @echo off
    setlocal EnableExtensions EnableDelayedExpansion
    for /R %%I in (???????????account.txt) do (
        set "FileName=%%~nI"
        set "NewFileName=MSF!FileName:~9,2!DNB.abc"
        if not exist "%%~dpI!NewFileName!" (
            ren "%%~fI" "!NewFileName!" 2>nul
            if not exist "%%~dpI!NewFileName!" echo Failed to rename file: "%%~fI"
        ) else (
            echo Cannot rename file: "%%~fI"
        )
    )
    endlocal
    

    The file name of found account text file is assigned to environment variable FileName.

    The new name for the file is created by concatenating the fixed parts MSF and DNB.abc with the 2 characters to keep from file name using string substitution and delayed expansion.

    Next it is checked if a file with new name does not already exist. Is this the case the file renaming is done otherwise an error message is output.

    After renaming the file it is checked if that was successful. A slightly different error is output if renaming failed for example because of a sharing violation.

    For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

    • echo /?
    • endlocal /?
    • for /?
    • if /?
    • ren /?
    • set /?
    • setlocal /?

    Read also the Microsoft article about Using Command Redirection Operators.