Windows Batch File to Replace String in Filename

batchcommand linewindows

I'm trying to batch rename files in a folder containing files in the following name pattern:

xxxtemplatexxxxx.xlsx

One example of the name I'd have is:

IDA_template - differentwordingshere.xlsx

The x's may not be the same. I want to replace template with the date, for example 201307.

I tried

ren *template* *201307*

But it appended 201307 to the end instead.

In bash I could probably do

rename template 201307 *.xlsx

but unfortunately this will be on Windows.

.bat file will be placed in the same folder as where the files are.

Best Answer

@echo off
setlocal enabledelayedexpansion

for %%F in (*template*) do (
    set name=%%~nxF
    set name=!name:template=%date:~-4%%date:~-10,2%!
    rename "%%~fF" "!name!"
)

exit /B 0
Related Question