简体   繁体   中英

In a batch file, how do I delete all files NOT of a certain type

I'm writing a batch file that needs to delete all the files in a certain dir and all of it's subdirectories except those of a specific type.

How can I do this?

I wrote this batch file after a coworker asked for help with deleting all the files EXCEPT for those of certain types from a folder and all subfolders, while maintaining the directory structure. I would recommend backing up your folder before attempting this. Just open up notepad and paste the following, save it as a .bat instead of a .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%

I'm using the solution found here: How can I delete all files/subdirs except for some files in DOS?

give it a go :)

You might try something along the lines of

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 the following:

robocopy source_folder target_folder *.java /s

or

xcopy *.java target_folder /s

which keeps the directory structure but only copies .java files.

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

The /s copies subdirectories

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

Try researching here .

Although it doesn't give you exactly what you are asking, I would say it's a good starting point.

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

The variable, address, is the directory and the variable, theType, is the type you do not want to delete.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM