【问题标题】:Batch file that keeps the 7 latest files in a subfolder将 7 个最新文件保存在子文件夹中的批处理文件
【发布时间】:2016-10-03 11:04:09
【问题描述】:

谁能帮我创建一个批处理文件?基本上,我的目标是创建一个批处理文件,将最新的 7 个文件(换句话说,最新的)保存在指定目录的所有文件夹中。

我明白了

set file2del=
for /f "skip=7" %%A in ('dir /b/o-d') do set file2del=%%A
if not "%file2del%"=="" del "%file2del%"

但这适用于当前目录。

【问题讨论】:

    标签: file batch-file delete-file


    【解决方案1】:

    试试这个:

    首先使用FOR /D/R 开关在所有文件夹上递归循环(从 bat 开始的地方)。并在每个目录上应用FOR /F 循环。

    @echo off
    
    for /d /r %%a in (*) do (echo Treating Diretory ==^>  %%a
      for /f "skip=7" %%b in ('dir /b/o-d "%%a"') do del "%%a\%%b"
    )
    

    如果您需要更详细的信息,可以使用计数器代替 SKIP=7

    @echo off
    setlocal enabledelayedexpansion
    
    
    for /d /r %%a in (*) do (echo Treating Diretory ==^>  %%a
      set /a $count=1
      for /f %%b in ('dir /b/o-d "%%a"') do (
              if !$count! LEQ 7 (
                  echo Keeping File[!$count!] ==^> %%b
                  set /a $count+=1
              ) else (echo Deleting File ==^> %%a\%%b
                      del "%%a\%%b")
       )
    )
    

    【讨论】:

      【解决方案2】:
      set "specificDir=c:\temp\"
      for /f "skip=7" %%A in ('dir /b /o-d /a-d "%specificDir%"') do del "%%~fA"
      

      应该这样做。我添加了/a-d 以排除文件夹,使用%%~fA 获取包括驱动器/路径在内的完整文件名,并在其周围加上引号以安全地处理带有空格的文件名(或路径)。

      【讨论】:

        猜你喜欢
        • 2021-08-26
        • 1970-01-01
        • 1970-01-01
        • 2017-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多