6

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.

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. That works. It even works without adding, "eol=: delims=". May I know what is the reason for using it in the above command line? Also, the additional arguments to the dir command other than /b. I understand the use of /b switch however, what is the use of /a-d?
Use HELP DIR from the command line for help on all the options. But /a-d excludes folders from the output. DELIMS should be set to nothing to preserve the entire file name. The default of space and tab would break at the first space in a file name. A ; is a valid file name character. Any file name starting with ; would be ignored by FOR with the default EOL option. No file name can contain a :, so I set the EOL option to that character.
3

The answer from Aacini worked for me. I needed a bat file to parse the directory tree finding all files with xyz file extension and not containing 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
   )
)

1 Comment

This isn't really different from Aacini's answer. What does it add?
2
setlocal EnableDelayedExpansion
for %i in (*.*) do (set "name=%i" & if "!name!" == "!name:sample=!" del /f /q %i)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.