0

I scoured the web and could not find the exact code I'm looking for... I found things that are very similar but did not get them to work. Here is a rough idea what I want:

int i = 1;
FOR (i; i < 9999; i++)
IF EXIST filename.log THEN
REN filename%i%.log
ELSE IF EXIST filename%i%.log THEN
REN filename%(i+1)%.log

Basically I want to check if a filename exists and if so, rename it to filename0001 -- from there on, each time the batch is run, if filename#### is found, it renames it to one after that. So of course after the first time this is run, when it finds that filename exists it will rename it to filename0002 and so on.

Thank you!!

1 Answers1

3

Edited in response to comment. Also added test to make sure debug.log exists. Don't want to rename files unnecessarily

This 1st solution always has the most recent log as debug.log, the next most recent as debug0001.log, the next as debug0002.log, etc. The oldest log will have the highest number.

@echo off
setlocal enableDelayedExpansion
set "base=debug"
if exist "%base%.log" for /f "eol=: delims=" %%F in (
  'dir /b /o-n "%base%*.log" ^| findstr /rix /c:"%base%.log" /c:"%base%[0-9][0-9][0-9][0-9].log"'
) do (
  set "name=%%~nF"
  set /a "n=10000!name:*%base%=! %% 10000 + 1"
  ren "%%F" "%base%!n!.log"
)

To make the oldest log have 0001 and the newest have the highest number, then a small change is needed. Only one rename is needed.

@echo off
setlocal enableDelayedExpansion
set "base=debug"
if exist "%base%.log" for /f "eol=: delims=" %%F in (
  'dir /b /o-n "%base%*.log" ^| findstr /rix /c:"%base%.log" /c:"%base%[0-9][0-9][0-9][0-9].log"'
) do (
  set "name=%%~nF"
  set /a "n=10000!name:*%base%=! %% 10000 + 1"
  ren "%base%.log" "%base%!n!.log"
  goto :break
)
:break
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • Oh, shoot, sorry. The log file being renamed will not have numbers. So it will always be "debug.log" and I'll be renaming it (adding numbers, effectively). Thus the first time, debug.log renames to debug001(orwhatever).log, next time debug.log renames to debug002.log, etc. –  Jul 11 '12 at 21:29
  • @user1502648 - OK, I think the 2nd set of code does what you are looking for. – dbenham Jul 11 '12 at 21:42