Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOS Batch FOR Loop to delete Files not Containing a String

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.

like image 205
Neon Flash Avatar asked May 28 '12 16:05

Neon Flash


People also ask

What is %% in a batch file?

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.

How do I delete certain files using command prompt?

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.


Video Answer


3 Answers

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
   )
)
like image 36
user3052500 Avatar answered Oct 24 '22 10:10

user3052500


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.

like image 187
dbenham Avatar answered Oct 24 '22 10:10

dbenham


setlocal EnableDelayedExpansion
for %i in (*.*) do (set "name=%i" & if "!name!" == "!name:sample=!" del /f /q %i)
like image 2
Aacini Avatar answered Oct 24 '22 10:10

Aacini