如何删除文件夹及其子文件夹中的所有文件,但 Windows 中具有特定名称的文件除外 7

How to delete all the files in a folder and its sub folders, except one file with particular name in Windows 7

基本上, 假设我有一个示例文件夹如下:

C:\
└───Dox
    │   cat.txt
    │   dog.txt
    │   girl.txt
    │   ...
    │
    └───NonDOx
            boy.txt
            girl.txt
            ...

我希望它看起来像这样,

C:\
└───Dox
    │   girl.txt
    │
    └───NonDOx
            girl.txt

所以,是的,基本上,文件夹和子文件夹中的所有文件都应该删除,除了位于随机文件夹中的 girl.txt。 另外,文件夹和目录有什么区别?是不是像一个 directory 是一个包含一个或多个文件夹的文件夹,还是与文件夹相同?

我找不到可以在子文件夹中删除并留下 1(特定文件)的内容。

我会按以下方式进行:

rem /* Loop over all items (both files and sub-directories) in the root directory recursively;
rem    then sort them in reverse alphabetic manner, so lower directory hierarchy levels appear
rem    before higher ones and files appear before their parent sub-directories: */
for /F "delims= eol=|" %%F in ('dir /S /B /A "C:\Dox\*.*" ^| sort /R') do (
    rem // Check whether current item is a file (note the trailing `\` to match directories):
    if not exist "%%F\" (
        rem // The current item is a file, hence check its name and delete if not matching:
        if /I not "%%~nxF" == "girl.txt" del "%%F"
    ) else (
        rem // The current item is a sub-directory, hence try to remove it; this only works
        rem    when it is empty; the `2> nul` prefix suppresses potential error messages:
        2> nul rd "%%F"
    )
)

删除除...之外的所有文件的最简单(也是最安全)方法是仅将这些文件复制到备份文件夹,删除整个原始目录,然后将备份文件放回原处。我称之为安全的原因是,如果所有需要的文件都在那里,您可以检查备份目录:(未测试)

xcopy /S girl.txt <Backup_Directory>\
cd <Backup_Directory>
tree /F //verify if everything is well copied
rmdir <original_directory>
xcopy /S <Backup_Directory>\ <original_directory>\