Batch File to Rename Files

Calsceron

2[H]4U
Joined
Oct 5, 2001
Messages
2,116
I would like a DOS-based batch script that takes all files within the current directory and renames them with the current date in YYYYMMDD-[Sequence Number padded to 3 digits]- and changes the extension to scr as follows:
alpha.txt becomes 20090723-001-.scr
beta.txt becomes 20090723-002-.scr
charlie.txt becomes 20090723-003-.scr

...
For the sequence increment, I have this but it's stripping off leading zeroes, (making it useless until I reach the 100th file):
set S=001
for %%F in (*.TXT) do (
set /A S += 1
ren "%%F" !S!%%~xF
)


/Edit:
The delim command can be used to hard code the century, and then parse the computer date for the date portion of the filename.
for /f "tokens=1-9 delims=/ " %%d in ("%date%") do rename "*.txt" 20%%f%%d%%e-###-.scr
The solution doesn't have to be pretty. It just needs to function.
 
Last edited:
keeping my eye on this because I would like to see the final answer
 
To be clear I'm using XP machine with cmd.exe, which is not the same as DOS. I apologize if cmd.exe is not considered true programming, but I can't find a better place on this forum to place this request...

In case anyone is interested, I modified a script I found on the Internet to address the sequencing issue:

@echo off&setlocal&set count=0
for /f "usebackq delims=" %%x in (`dir /a:-d /b "*.TXT"`) DO CALL :NUMBER %%x
goto :EOF
:NUMBER
set NAME=%~n1%
set EXT=00%count%
set EXT=%EXT:~-3%
echo ren "%1" "-%EXT%-.scr"
set /a count+=1
goto :EOF


so this will convert alpha.txt to -001-.scr, beta.txt to -002-.scr, etc., now all is left to do is append the date, and I'm all set.
 
Last edited:
If you have access to a Perl interpreter, this will do it:
Code:
my $date = ((localtime(time))[5]+1900) . sprintf("%02d",(localtime(time))[4]) . sprintf("%02d",(localtime(time))[3]);
my $seq = 0;
foreach my $file (<*.txt>) {
	my $newName = sprintf("%s-%03d-.scr", $date, $seq++);
	(rename($file, $newName) and print "$file -> $newName\n") or warn "Warning: could not rename $file\n";
}
 
Back
Top