jduff
I'm maintaining a folder that contains log files of the form log.0001, log.0002, log.0003, etc. The log numbers continually increase, and the newest log file extension is set to the highest number. However, because of space limitations I want to keep only the last 3 log files.
I've written the following batch file which deletes all but the three log files with the highest extension numbers:
Code: Select all
@echo off
setlocal enabledelayedexpansion
set myDir=Z:\whatever
REM Find the total number log files in the directory.
set /A total=0
for %%v in ("%myDir%\log.*") do (
set /A total+=1
)
REM Delete all but the last 3 log files.
set /A delCount = total-3
set /A count=1
for %%v in ("%myDir%\log.*") do (
if /i "!count!" LEQ "!delCount!" del %%v
set /A count+=1
)
I can list the files in reverse order on the command line using "dir .\journal.* /O-E". However, I don't know how to use this command/information to reverse the order of the files in the script's loop. Can the script be re-written to use only one loop which iterates over the log files in reverse order?
jduff
----------------------------
#3 06 Mar 2007 16:33
bluesxman
This should do the trick:
Code: Select all
@echo off
setlocal enabledelayedexpansion
set myDir=Z:\whatever
set count=0
REM If it were me, I'd use "dir /b /o-d" below so that we are depending on the created date, rather than the extension
for /f "usebackq tokens=*" %%a in (`dir /b /o-e "%myDir%\log.*"`) do (
set /a count+=1
if !count! GTR 3 (
echo:Deleting: %%~a
del "%myDir%\%%~a"
) ELSE (
echo:Keeping: %%~a
)
)
cmd | *sh | ruby | chef
----------------------------
#4 15 May 2007 12:30
sotirov
You can use the following one line code, to delete all the files in a directory, keeping the newest 3 (last 3 created).
Code: Select all
@echo off
set myDir=Z:\whatever
for /f "tokens=* skip=3" %%F in ('dir %myDir% /o-d /tc /b') do del %myDir%\%%F
----------------------------
#5 16 May 2007 15:07
bluesxman
Very neat. You've no idea how annoyed I am with myself for not thinking of that!

cmd | *sh | ruby | chef
related: How to find the newest file between several files