[英]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. 我想删除Documents目录下不是.doc的所有文件。 How can I do this with a windows batch file or in the command prompt? 如何使用Windows批处理文件或在命令提示符下执行此操作?
@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 /ad
) to retrieve the list of files under the documents folder. 此代码执行dir命令(仅文件路径/名称/b
,递归/s
,列表/ad
没有文件夹)以检索document文件夹下的文件列表。 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"
使用findstr
过滤此列表,以仅获取(忽略大小写/i
在行/e
末尾不包含/v
的行,即文本/l
.doc /c:".doc"
This command is executed from a for
command that will process each line of the output. 该命令从for
命令执行,该命令将处理输出的每一行。 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. 对于每一行,可替换参数%%a
将保存文件的路径/名称,因此在do
子句中,我们删除了所指示的文件。
del
operations are only echoed to console. 仅将del
操作回显到控制台。 If the output is correct, remove the echo
command 如果输出正确,请删除echo
命令
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
使用forfiles
命令:
forfiles /s /c "cmd /c if @isdir NEQ TRUE if [@ext] NEQ [doc] del @path"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.