为了运行一个批处理文件,该文件将在R:\中的所有文件夹中进行搜索,但exculde_dir.txt中的文件除外,然后删除所有与exclude_FILE.txt中扩展名不匹配的文件
我一直在指一个有效的答案,
Iterate all files in a directory using a 'for' loop 稍作修改,如下:
for %%f in (R:\*) do ( something_here ^| findstr /I /V /L /G:"R:\exclude_FILE.txt")
结合另一个答案:
Windows 'findstr' command: Exclude results containing particular string
for /F "delims=" %%D in ('dir /B /S /A:D "R:" ^| findstr /I /V /L /G:"R:\exclude_DIR.txt"') do echo/%%D
请考虑以下理论结构:
R:\DIR1\file.jpg
R:\DIR1\file.mkv
R:\DIR1\file.txt
R:\DIR2\file.jpg
R:\DIR2\file.mkv
R:\DIR2\file.txt
R:\DIR3\file.jpg
R:\DIR3\file.mkv
R:\DIR3\file.txt
R:\$RECYCLE.BIN
其中文件的内容排除在外_FILE.txt
.mkv
.avi
.m4v
和exculde_DIR.txt
$RECYCLE.BIN
DIR2
,但语法不正确。我希望仅.mkv文件保留在DIR1和DIR3中,并且不排除任何其他目录,并且不影响排除的DIR2和回收站。谢谢!
答案 0 :(得分:0)
使用findstr
command,无需将目录与文件分开,您可以使用正则表达式(exclude.txt
)在单个排除文件(例如/R
)中指定它们,而不用文字字符串(/L
),可能看起来像这样(#
和后面的所有内容都不是文件内容的一部分;请确保没有结尾的空格):
\\DIR2\\ # directory names in file paths must be given within literal `\`; # this avoids partial directory names to match, like `myDIR2`, for instance; \\$RECYCLE\.BIN\\ # literal `\` must be stated as `\\`, literal `.` as `\.`; # also `[` and `]` needed to be escaped like `\[` and `\]`, respectively; \.mkv$ # the trailing `$` symbol anchors the extension to the end of a file path; \.avi$ \.m4v$
适合的代码在这里:
rem // Note that the exclusion file must be placed in the same directory as this script!
for /F "delims=" %%I in ('
dir /S /B /A:-D "R:\*.*" ^| findstr /I /R /V /G:"%~dp0exclude.txt"
') do (
ECHO del "%%I"
)
在测试了代码之后,删除大写的ECHO
命令以实际删除文件。
也许最好将脚本和排除文件放在目标目录树中,以免它们也被删除。如果不能保证,可以扩展脚本,以便脚本自动自动执行以下排除操作:
rem // Note that the exclusion file must be placed in the same directory as this script!
rem // Assign path the exclusion file to a variable:
set "EXCLUDE=%~dp0exclude.txt"
rem // Convert path of this script to a regular expression suitable for `findstr`:
call :CONVERT BATCH "%~f0"
rem // Convert path of exclusion file to a regular expression suitable for `findstr`:
call :CONVERT EXCLF "%EXCLUDE%"
for /F "delims=" %%I in ('
dir /S /B /A:-D "R:\*.*" ^| ^
findstr /I /R /V /G:"%EXCLUDE%" /C:"^%BATCH%$" /C:"^%EXCLF%$"
') do (
ECHO del "%%I"
)
exit /B
:CONVERT
rem // The first command line argument is a variable name;
rem // Assign second command line argument to a variable:
set "STR=%~2"
rem // Escape certain characters that have special meaning to `findstr`:
set "STR=%STR:\=\\%"
set "STR=%STR:.=\.%"
set "STR=%STR:[=\[%"
set "STR=%STR:]=\]%"
rem // Assign result to given variable:
set "%~1=%STR%"
exit /B