0

我有一个包含混合日志文件的文件夹 - 例如:

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

我需要一个快速的小批处理文件来清除 A、B 和 C 中除最近(按日期)3 个文件之外的所有文件。

我可以删除文件夹中除他最近的 3 个文件之外的所有文件:

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

但我不确定如何在不硬编码 A、B 和 C 并执行 3 个单独循环的情况下添加命名约定(如果 D 出现,则它会被完全忽略)。

有任何想法吗?

好的,我想通了:

@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 回答