DOS Batch FOR Loop to delete Files not Containing a String

batch-file, for-loop

Solution

Easiest to use FIND or FINDSTR with `/V` option to look for names that don't contain a string, and `/I` option for case insenstive search. Switch to `FOR /F` and pipe results of `DIR` to `FIND`.

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

change %F to %%F if used in a batch file.

Problem

I want to delete all the files in the current directory which do not contain the string "sample" in their name. for instance, ``` test_final_1.exe test_initial_1.exe test_sample_1.exe test_sample_2.exe ``` I want to delete all the files other than the ones containing sample in their 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.

Original source