【问题标题】:In a batch file, how do I delete all files NOT of a certain type在批处理文件中,如何删除所有非特定类型的文件
【发布时间】:2009-05-14 14:12:39
【问题描述】:

我正在编写一个批处理文件,它需要删除某个目录中的所有文件及其所有子目录除了特定类型的文件。

我该怎么做?

【问题讨论】:

  • 或者更好的是,如何在保持目录结构的同时从一个目录(及其所有子目录)复制某种类型的所有文件 (*.java)?
  • 不能只复制某种类型的所有文件,同时用XCOPY保持目录结构,然后删除其余的吗?
  • @Mitch Wheat:既然 Monster 已经放了“batch”标签,我想他希望有一个脚本解决方案,所以它与编程相关。
  • 强烈反对关闭为“与编程无关”。

标签: windows batch-file cmd dos


【解决方案1】:

在一位同事请求帮助删除文件夹和所有子文件夹中某些类型的文件以外的所有文件,同时保持目录结构后,我编写了这个批处理文件。我建议在尝试此操作之前备份您的文件夹。只需打开记事本并粘贴以下内容,将其保存为 .bat 而不是 .txt 祝你好运! 〜卡罗琳

REM Use at your own risk, it does a mass DELETE of everything!

SET /p ExcludeFiles=What file type should be kept (NOT deleted)? Type the file name(s) inside parantheses. example: (pdf) or (shp dbf shx)     
SET /p MapDrive=What drive letter is the folder in? example: c or n     
SET /p Directory=Drag the folder you would like to modify into this command prompt then press ENTER.     

%MapDrive%:
cd %Directory%

attrib +a *.* /s
echo %date%
for %%i in %ExcludeFiles% do attrib -a *.%%i /s
echo %date%
del %Directory%\*.* /s /a:a /q

echo %date%
attrib +a %Directory%\*.* /s
echo %date%

【讨论】:

    【解决方案2】:

    你可以尝试一下

    for /f "usebackq delims=" %i in (`dir /s /b *`) do if not %~xi==.txt del %i
    

    对于您在评论中的问题,您可以尝试以下操作:

    robocopy source_folder target_folder *.java /s
    

    xcopy *.java target_folder /s
    

    保持目录结构但只复制.java文件。

    【讨论】:

      【解决方案3】:

      最安全的方法是复制所有您想要的文件并删除其余文件。
      XCOPY *.java c:\new_directory /s

      /s 复制子目录

      【讨论】:

        【解决方案4】:

        我正在使用此处找到的解决方案: How can I delete all files/subdirs except for some files in DOS?

        试一试:)

        【讨论】:

          【解决方案5】:

          尝试研究here

          虽然它不能准确地告诉你你的要求,但我会说这是一个很好的起点。

          【讨论】:

            【解决方案6】:

            你可以试试这个:

            ECHO DIR %address% /S /B | FIND /C %theType%>temptemp.txt
            FOR /f %%a IN (temptemp.txt) DO DEL %%a
            DEL temptemp.txt
            

            变量address是目录,变量theType是您不想删除的类型。

            【讨论】:

              【解决方案7】:
              FORFILES /s /p c:\dir /c "if not @ext==.txt del /f @file"
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2021-12-07
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2012-10-19
                • 1970-01-01
                • 2023-01-10
                • 1970-01-01
                相关资源
                最近更新 更多