DOS Batch FOR Loop to delete files that do not contain a string

I want to delete all files in the current directory that do not contain the string "sample" in their name.

eg,

test_final_1.exe test_initial_1.exe test_sample_1.exe test_sample_2.exe 

I want to delete all files other than those that contain a sample in the name.

 for %i in (*.*) do if not %i == "*sample*" del /f /q %i Is the use of wild card character in the if condition allowed? Does, (*.*) represent the current directory? 

Thanks.

+6
source share
3 answers

The easiest way is to use FIND or FINDSTR with the /V option to search for names that do not contain a string, and /I to search in insenstive. Switch to FOR /F and pipe results from DIR to FIND .

 for /f "eol=: delims=" %F in ('dir /b /ad * ^| find /v /i "sample"') do del "%F" 

change the value of% F to %% F, if used in a batch file.

+6
source
 setlocal EnableDelayedExpansion for %i in (*.*) do (set "name=%i" & if "!name!" == "!name:sample=!" del /f /q %i) 
+2
source

The answer from Aacini worked for me. I needed a bat file to analyze the directory tree, in which all files with the xyz file extension were found and did not contain badvalue anywhere in the path. The solution was:

 setlocal enableDelayedExpansion for /r %%f in (*.xyz) do ( set "str1=%%f" if "!str1!" == "!str1:badvalue=!" ( echo Found file with xyz extension and without badvalue in path ) ) 
+2
source

Source: https://habr.com/ru/post/916859/


All Articles