I have been trying to create a batch script which will delete specific files from a location. The files that are NOT to be deleted are listed in a separate file called list.txt.
So far it works if the entire filename + extension is written in the list.txt like this:
abcapplefruit.jpg 12345numbertext.png moon1234sun.htm
What I would like to have is to write only a part of the filename in the list.txt like this:
apple number sun
And then skip these files containing these words from deletion.
What I have managed to do is the following:
@echo off
setlocal
set "folder=C:\Users\abc\Desktop\WindowsBatch\Log"
set "excludeFile=%folder%\list.txt"
setlocal enableDelayedExpansion
:: 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. && echo Target folder does not exist.
if not exist "%excludeFile%" echo %~nx0: The list file doesn't exist at the location specified! && echo List file does not exist.
for /f "delims=" %%F in ('dir /b /a-d "%folder%\"') do Call :process_file "%%F" "%~1" "%excludeFile%"
goto :EOF
:: --------------------------------------------
:process_file
:: --------------------------------------------
set input_file=%~1
set list_file=%~nx3
echo Input file: "%input_file%"
:: Skip list file and this batch file too
if "%list_file%"=="%input_file%" echo Skip list file && goto :EOF
::echo This batch file = Input file: "%this_batch%"=="%input_file%"
echo list file = input file: "%list_file%"=="%input_file%"
:: Grep for the include file in the list
findstr "%input_file%" "%excludeFile%" 2>&1 1>NUL && goto :EOF
:: 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
pause
del %folder%\%input_file%
echo %folder%\%input_file%
pause