首页 > 解决方案 > 如果在文本 txt 文件的列表中找不到文件,则 CMD 批处理文件删除文件

问题描述

我需要一个蝙蝠来删除文本文件中不包含的所有具有相对名称的文件

在文本文件 list.txt 我有这个:

C:\S-ATLANTICO-1\MEDIA\Innplay-Logo.mp4
C:\S-ATLANTICO-1\MEDIA\logo-FB_sep.png
C:\S-ATLANTICO-1\MEDIA\logo-news_sa.png

并且在同一文件夹中有以下文件:

Innplay-Logo.mp4
logo-FB_sep.png
logo-news_sa.png
Carlos.jpg
Sapo.png
list.txt

所以我需要删除下一个文件,因为 list.txt 中不存在

Carlos.jpg
Sapo.png

但我也必须保留 LIST.TXT

我试过这个但没有成功

@echo off
setlocal
set "folder=C:\S-ATLANTICO-1\MEDIA"
set "excludeFile=C:\S-ATLANTICO-1\MEDIA\list.txt"
for /f "eol=: delims=" %%F in ('dir /b /a-d "%folder%" ^| findstr  /vig:"%excludeFile%" ^| findstr /v /i "\list.txt"') do del "%folder%\%%F"

任何人都可以帮助我。

谢谢

标签: windowsbatch-filecmd

解决方案


试一试。它适用于我的测试。

我放置了echo语句,而不是实际删除任何内容。

@echo off
setlocal
set "folder=C:\S-ATLANTICO-1\MEDIA"
set "excludeFile=%folder%\list.txt"

:: Check that both the target folder and filter file exist before starting up.
if not exist "%folder%" echo %~nx0: The target folder doesn't exist.  Nothing to do.&& goto :EOF
if not exist "%excludeFile%" echo %~nx0: The list file doesn't exist at the location specified!&& goto :EOF

for /f "delims=" %%F in ('dir /b /a-d "%folder%"') do call :process_file "%%F" "%~0" "%excludeFile%"
goto :EOF

:: --------------------------------------------
:process_file
:: --------------------------------------------
set input_file=%~1
set this_batch=%~2
set list_file=%~nx3

:: Skip list file and this batch file too
if "%this_batch%"=="%input_file%" echo Skip this batch file&& goto :EOF
if "%list_file%"=="%input_file%" echo Skip list file&& goto :EOF

:: Grep for the include file in the list 
findstr /C:"%input_file%" "%excludeFile%" 2>&1 1>NUL

:: Bail out if the input line was in the list file
if not errorlevel 1 echo Skip "%input_file%", it is in %list_file%&& goto :EOF

:: Delete anything left
echo delete file %input_file%&& goto :EOF
goto :EOF

推荐阅读