【问题标题】:Delete all files in folder except file in list using batch使用批处理删除文件夹中的所有文件,但列表中的文件除外
【发布时间】:2014-06-06 08:25:09
【问题描述】:

我在一个文件夹(临时文件夹)中有三个文件

1.txt
2.exe
3.txt

现在我将使用批处理编写脚本来删除文件夹中除一个文件(3.txt)之外的所有文件。怎么写成脚本。我尝试使用

del temp /Q

但它会删除我文件夹中的所有文件。我不想全部删除。我只想删除1.txt和2.exe。假设文件数量很大。

【问题讨论】:

    标签: windows string batch-file


    【解决方案1】:

    如果您遍历目录的内容,您可以应用您可能想要的任何逻辑,并对这些内容执行您可能想要的任何操作。示例:

    @echo off
    
    setlocal enableextensions enabledelayedexpansion
    
    set dirPath=C:\Users\BuvinJ\Desktop\test
    
    pushd !dirPath!
    
    :: Loop through all files in this directory 
    for %%a in (*) do (
        set fileName=%%a
        if "!fileName!"=="1.txt" (
            echo FOUND: !fileName!
        ) else (
            echo OTHER: !fileName!
        )
    )
    
    :: Loop through all sub directories in this directory
    for /d %%a in (*) do (
        set dirName=%%a
        echo Directory: !dirName!
    )
    
    popd
    

    您可能还想“递归地”逐步浏览内容,即向下钻取到嵌套的子目录。为此,请在 for 语句后添加 /r(如示例中的 /d 以遍历目录而不是文件)。

    有关这种循环的更多信息,请查看:http://ss64.com/nt/for2.html

    【讨论】:

      【解决方案2】:

      你可以使用命令

      except 3.txt del temp /Q
      

      它将删除文件夹中除3.txt之外的所有文件

      【讨论】:

      • 您使用的是什么版本的批处理/Windows 命令提示符?我从来没有见过“except”,当我尝试这个时我抛出了一个错误。此外,这种语法对于批处理来说看起来很奇怪......
      • 我认为你必须在路径上添加这批:stackoverflow.com/a/558677/1952213
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多