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.
Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
Force delete using Windows With the command prompt open, enter del /f filename , where filename is the name of the file or files (you can specify multiple files using commas) you want to delete.
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
)
)
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.
setlocal EnableDelayedExpansion
for %i in (*.*) do (set "name=%i" & if "!name!" == "!name:sample=!" del /f /q %i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With