In a batch file, how to delete all NOT files of a specific type

I am writing a batch file that must delete all files in a specific directory and all its subdirectories except for a specific type.

How can i do this?

+1


a source to share


7 replies


I wrote this batch file after a colleague asked for help with removing all EXCEPT files for those of a specific type from a folder and all subfolders, while preserving the directory structure. I would recommend backing up your folder before attempting this. Just open notepad and paste the following, save it as .bat instead of .txt Good luck! ~ Carolyn



REM Use at your own risk, it does a mass DELETE of everything!

SET /p ExcludeFiles=What file type should be kept (NOT deleted)? Type the file name(s) inside parantheses. example: (pdf) or (shp dbf shx)     
SET /p MapDrive=What drive letter is the folder in? example: c or n     
SET /p Directory=Drag the folder you would like to modify into this command prompt then press ENTER.     

%MapDrive%:
cd %Directory%

attrib +a *.* /s
echo %date%
for %%i in %ExcludeFiles% do attrib -a *.%%i /s
echo %date%
del %Directory%\*.* /s /a:a /q

echo %date%
attrib +a %Directory%\*.* /s
echo %date%

      

+2


a source


You can try something along the lines

for /f "usebackq delims=" %i in (`dir /s /b *`) do if not %~xi==.txt del %i

      

For your question in the comment, you can try this:

robocopy source_folder target_folder *.java /s

      



or

xcopy *.java target_folder /s

      

which preserves the directory structure but only copies files .java

.

+1


a source


The safe way is to copy all the files you want and delete the rest.
  XCOPY * .java c: \ new_directory / s

/ s copies subdirectories

+1


a source


I am using the solution found here: How do I delete all files / sub-files except some files in DOS?

let it go :)

+1


a source


Try researching here .

While this doesn't give you exactly what you're asking, I would say it's a good starting point.

0


a source


You can try this:

ECHO DIR %address% /S /B | FIND /C %theType%>temptemp.txt
FOR /f %%a IN (temptemp.txt) DO DEL %%a
DEL temptemp.txt

      

Variable, address is directory and variable, typeType is the type you don't want to remove.

0


a source


FORFILES /s /p c:\dir /c "if not @ext==.txt del /f @file"

      

0


a source







All Articles