我正在尝试使用批处理脚本从目录及其子目录中删除所有非代码文件。使用命令提示符,我可以验证脚本的结果,但当执行脚本时,它没有执行人们所期望的操作。
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”应该做的那样指向一个文件?