我正在尝试使用批处理脚本从目录及其子目录中删除所有非代码文件。使用命令提示符我可以验证脚本的结果,但是当脚本执行时,它不会执行人们期望的操作。
for /F %%F in ('dir /s /b /a-d ^| findstr /vile ".c .cpp .h .hpp"') do if "%%~fF" neq "%~f0" del /S /Q "%%F"
提取并执行以下命令时,生成的路径是正确的:
dir /s /b /a-d | findstr /vile ".c .cpp .h .hpp"
但是,当通过批处理文件执行它时,发送到'del /S /Q "%%F"' 命令的结果路径一遍又一遍地是第一个子目录。
下面是命令提示符输出和批处理文件输出的对比(将del命令替换为echo)
安慰:
C:\testdata\delete_test>dir /s /b /a-d | findstr /vile ".c .cpp .h .hpp"
C:\testdata\delete_test\delete_non_code_files.bat
C:\testdata\delete_test\delete_test - Copy\7328_log.txt
C:\testdata\delete_test\delete_test - Copy\7588_log.dat
C:\testdata\delete_test\delete_test - Copy\7964_log.txt
C:\testdata\delete_test\delete_test - Copy\8860_log.txt
C:\testdata\delete_test\delete_test - Copy (2)\7328_log.txt
C:\testdata\delete_test\delete_test - Copy (2)\7588_log.dat
C:\testdata\delete_test\delete_test - Copy (2)\7964_log.txt
C:\testdata\delete_test\delete_test - Copy (2)\8860_log.txt
C:\testdata\delete_test\delete_test - Copy (3)\7328_log.txt
C:\testdata\delete_test\delete_test - Copy (3)\7588_log.dat
C:\testdata\delete_test\delete_test - Copy (3)\7964_log.txt
C:\testdata\delete_test\delete_test - Copy (3)\8860_log.txt
批处理文件:
C:\testdata\delete_test>delete_non_code_files.bat
/S /Q "C:\testdata\delete_test\delete_test"
/S /Q "C:\testdata\delete_test\delete_test"
/S /Q "C:\testdata\delete_test\delete_test"
/S /Q "C:\testdata\delete_test\delete_test"
/S /Q "C:\testdata\delete_test\delete_test"
/S /Q "C:\testdata\delete_test\delete_test"
/S /Q "C:\testdata\delete_test\delete_test"
/S /Q "C:\testdata\delete_test\delete_test"
/S /Q "C:\testdata\delete_test\delete_test"
/S /Q "C:\testdata\delete_test\delete_test"
/S /Q "C:\testdata\delete_test\delete_test"
/S /Q "C:\testdata\delete_test\delete_test"
为什么我的 %%F 变量不指向一个文件,因为 'for /F' 应该导致它这样做?