I have this batch script, but it is not renaming the files at all.
I have a list of documents that have been named in this format:
yyyymmdd_docname1.pdf
I try to rename all of the documents to docname1_yyyymmdd.pdf
.
Example to rename:
20230101_fullbloodcount.pdf
to fullbloodcount_20230101.pdf
.20230202_esr.pdf
to esr_20230202.pdf
What is constant for all these documents is the date format that is appended in front of the document name.
The script is as per below. I would appreciate if you could look over the script and let me know what is wrong with it.
@echo off
setlocal enabledelayedexpansion
set "directory=C:\Users\user1\Downloads\Rename"
cd /d "%directory%"
for %%f in (??????_*.pdf) do (
set "filename=%%~nf"
set "extension=%%~xf"
set "datepart=!filename:~0,8!"
set "docpart=!filename:~9!"
set "newname=!docpart!_!datepart!!extension!"
ren "%%f" "!newname!"
)
echo Files have been renamed.
pause
Here's a basic example of one way to approach the task:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "Directory=%UserProfile%\Downloads\Rename"
PushD "%Directory%" 2>NUL || GoTo :EOF
For /F "Delims=" %%G In ('Dir /A:-D /B "????????_*.pdf" 2^>NUL') Do (
If /I "%%~xG" == ".pdf" (
Set "_=%%~nG"
Set "$="
Set /A "$=%%~nG" 2>NUL
If Defined $ (
Set "#=%%G"
SetLocal EnableDelayedExpansion
If !$! GEq 19700101 (
If !$! LEq 20251231 (
Ren "!#!" "!_:~9!!_:~8,1!!$!%%~xG"
)
)
EndLocal
)
)
)
PopD
EndLocal
Exit /B
I have added some simple date validation to this code, (instead of relying upon up to any eight characters, or even a sequence of eight digits). The above is designed to work with all valid dates from 1970 up until the end of this year, (you would need to adjust the LEq
string beyond that). It does not however exclude invalid dates between those two, (e.g.20150229
or 20240931
), as doing so would be well beyond the requirements of your stated problem, and simple batch scripting.