Search code examples
batch-filecmdbatch-processingfile-renamebatch-rename

Re rename batch: how to change part of filenames in Batch


let's say I have main folder with many subfolders and inside them there are excel files. I want to change a certain part of filenames in all subfolders. I tried my best, but I am a new to Batch and I have no idea how to solve it. For example: - present version file123 2016.xlsx - expected version file123 2017.xlsx

My attempt:

@echo off
cd C:\example\

    setlocal EnableDelayedExpansion
    Set var1=2016
    Set var2=2017
    for /r %%G in (*.xlsx) do (
    set "filename=%%G"
    ren "!filename!" "!filename:%var1%=%var2%!"
)

Let me know if you've got any solution! Thx! :)


Solution

  • There is a trailing space in your line Set var1=2016. Batch is very picky about spaces, so the space is part of the variable. To avoid this, use the following syntax:

    set "var1=2016"
    

    Another error:

    ren /? says: ren [drive:][path]filename1 filename2
    You can't give a path for the destination name.

    Try this:

    for /r %%G in (*.xlsx) do (
        set "filename=%%~nxG"
        ren "%%G" "!filename:%var1%=%var2%!"
    )
    

    %%~nxG gives you name and extension only.