Page 1 of 1

Delete All but Last N Log Files

Posted: 2021-Jul-27, 6:14 pm
by MigrationUser
06 Mar 2007 07:19
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
)
The script above uses two loops, one to count the total number of log files in the directory, and one to remove the older log files. If I could get the second loop to iterate over the files in reverse order, I could delete all but the first 3 files in the second loop. Then, the first loop could be eliminated.

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
    )
)
Last edited by bluesxman (06 Mar 2007 16:39)

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
Of course logging of deleted files is also nice to be implemented as written in previous posts.

----------------------------

#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