Search code examples
batch-filebatch-rename

Batch script rename file


I have a file called xxxxxxx_12345.pdf and I try to delete the suffix and the result would be xxxxxxx.pdf. I tried following:

forfiles /S /M *_12545.pdf /C "cmd /c rename @file @fname*.pdf"

but it could not change the file name. Can somone help to solve this issue? thanks


Solution

  • I'm sure there is a way to do the job with forfiles command, however, it would be much easier to use regular for loop for this.

    @echo off
    pushd %~dp0
    setLocal EnableDelayedExpansion
    
    for %%f in (*_12545.pdf) do (
        set "CurrentFileName=%%~nf"
        set "RenameTo=!CurrentFileName:~0,-6!"
        echo.ren !CurrentFileName!%%~xf !RenameTo!%%~xf
    )
    
    pause>nul
    

    By setLocal EnableDelayedExpansion, user can use delayed environment variables, which will enable user to use something like !variable! instead of %variable%.

    set "CurrentFileName=%%~nf"
    

    %%~nf will give you the name of the file without extension, so in this case, CurrentFileName will be FileName_12545. Type for /? to see the full explanation of the syntax.

    set "RenameTo=!CurrentFileName:~0,-6!"
    

    Notice that I used !variable:~0,-6! to remove suffix. This is String Manipulation. The user is storing a string without suffix that has a length of 6 (which is _12545 in this case).

    echo.ren !CurrentFileName!%%~xf !RenameTo!%%~xf
    

    I placed echo in front of ren so you can check before you actually rename it. %%~xf will return the file extension including .(dot) in front of it. In this case, the file extension is .pdf.

    I hope this help a bit.