0

I have a folder containing a mix of log files - ex:

AAA.0.1.txt
AAA.0.2.txt
BBB.1.2.txt
BBB.1.3.txt
BBB.1.4.txt
CCC.0.5.txt
CCC.0.6.txt

I need a quick little batch file to clean out all but the most recent (by date) 3 files for each of A, B, and C.

I can delete the all but he most recent 3 files in the folder:

for /f "tokens=* skip=3" %%F in ('dir %myDir% /o-d /tc /b') do del %myDir%\%%F

but I'm not sure how to add in the naming convention without hardcoding A, B, and C and doing 3 separate loops (and if D shows up then it gets ignored altogether).

Any ideas?

Okay, I figured it out:

@echo off
setlocal enabledelayedexpansion
cls
set fileDir=C:\My\Log\Path
set prev=A
for /f "tokens=*" %%P in ('dir %fileDir% /o-d /tc /b') do (
    set fileName=%%P
    for /f "tokens=1,2,3,4 delims=. " %%a in ("!fileName!") do set proj=%%a

    if "!proj!" == "!prev!" (
        REM skip
    ) else (
        for /f "tokens=* skip=3" %%F in ('dir %fileDir%\!proj!.* /o-d /tc /b') do del %fileDir%\%%F
        set prev=!proj!
    )
)
4

1 に答える 1

0

I believe you want the last modified date, so I changed the option to /T2. Change back to /TC if you truly want creation date.

for /f "delims=." %%A in ('dir /a-d /b "%myDir%\*.*.txt"') do (
  for /f "skip=3 delims=" %%F in (
    'dir /a-d /o-d /tw /b "%myDir%\%%A.*.txt'
  ) do del "%myDir%\%%F"
)

The above is perhaps a bit inefficient since it will attempt to delete old files once for each file. You really only need to delete old files once per unique name prefix - that could be implemented, but I didn't think the added complexity was worth it. The above works just fine.

于 2013-02-05T17:33:06.063 に答える