【问题标题】:How to delete all the files in a folder and its sub folders, except one file with particular name in Windows 7如何删除文件夹及其子文件夹中的所有文件,Windows 7 中一个具有特定名称的文件除外
【发布时间】:2019-10-19 18:56:26
【问题描述】:

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

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

我希望它看起来像这样,

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

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

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

【问题讨论】:

  • bash 和批处理文件完全不相关,那么您要在什么环境下完成此操作?欢迎新用户Stack Overflow。请使用tour 并阅读How to Ask。 SO 既不是免费的脚本编写服务,也不是论坛,而是一个为程序员提供帮助的网站,帮助遇到明显问题的同事。预计会有自己的研究和认真的编码尝试。 Editminimal reproducible example 中包含您的 代码的问题。

标签: batch-file scripting windows-7-x64 delete-file


【解决方案1】:

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

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>\

【讨论】:

  • 删除和重新创建文件与保留文件不同,因为属性会丢失(例如,创建日期、所有者等);所以提问者必须决定这是否可以接受......
【解决方案2】:

我会这样做:

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"
    )
)

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 1970-01-01
    • 2012-12-15
    • 2018-06-21
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多