当前位置: 动力学知识库 > 问答 > 编程问答 >

How can I search within all subdirectories and delete all files that do not match the filetype in windows command prompt?

问题描述:

For example,

Documents

- Personal

- abc.doc

- 123.pdf

- Stuff

- def.doc

- 456.pdf

I want to delete all files that are not .doc under Documents directory. How can I do this with a windows batch file or in the command prompt?

网友答案:
@echo off
    setlocal enableextensions disabledelayedexpansion

    set "folder=x:\somewhere\documents"

    for /f "delims=" %%a in ('
        dir /b /s /a-d "%folder%" ^| findstr /i /v /e /l /c:".doc"
    ') do echo del "%%a"

This code executes a dir command (only file paths/names /b, recursive /s, without folders in the list /a-d) to retrieve the list of files under the documents folder. This list is filtered with findstr to only get, ignoring case /i, the lines that do not contain /v at the end of the line /e the literal /l .doc /c:".doc"

This command is executed from a for command that will process each line of the output. For each line, the replaceable parameter %%a will hold the path/name of the file, so in the do clause we remove the indicated file.

del operations are only echoed to console. If the output is correct, remove the echo command

网友答案:

Test this on a sample set of files.

@echo off
set "folder=c:\documents"
attrib +h "%folder%\*.doc" /s
del "%folder%\*.*?" /s
attrib -h "%folder%\*.doc" /s
网友答案:

use the underappreciated forfilescommand:

forfiles /s /c "cmd /c if @isdir NEQ TRUE if [@ext] NEQ [doc] del @path"
分享给朋友:
您可能感兴趣的文章:
随机阅读: