batch delete specific file type in subfolders

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
jaykappy
Posts: 1
Joined: 23 Aug 2016 12:30

batch delete specific file type in subfolders

#1 Post by jaykappy » 23 Aug 2016 12:47

I am trying to run a command that will search a bunc h of folders and DELETE ALL files EXCEPT a specific file.
I am using this right now.

for %i in (*) do if not %i == .msg del %i

Questions:
1. This does not work on subfolders. How do I modify it to do so?
2. How do I specify more than one type of file to KEEP (right now only the .msg are kept)
PLEASE HELP!!!!! Cheers

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: batch delete specific file type in subfolders

#2 Post by aGerman » 23 Aug 2016 13:14

This is for the cmd prompt:

Code: Select all

for /r %i in (*.msg) do ECHO del "%~fi"

You have to navigate to the folder you want to run the command beforehand.

You could also define the path where to start:

Code: Select all

for /r "C:\whatever path" %i in (*.msg) do ECHO del "%~fi"


Delete the ECHO command if it outputs the right files.

You have to double the percent signs if you want to run the FOR loop from within a batch script.

Steffen

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: batch delete specific file type in subfolders

#3 Post by foxidrive » 23 Aug 2016 18:03

It seems that the OP wants to exclude filetypes from the delete command.

This can be very slow if there are a bazillion number of files, otherwise it works.

Code: Select all

@echo off
set exclude=msg txt gif mp3 mkv
for /f "delims=" %%a in ('dir /b /s /a-d ^|findstr /ev "%exclude%" ') do del "%%a"

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: batch delete specific file type in subfolders

#4 Post by Squashman » 24 Aug 2016 15:14

jaykappy wrote:I am trying to run a command that will search a bunc h of folders and DELETE ALL files EXCEPT a specific file.
I am using this right now.

for %i in (*) do if not %i == .msg del %i

Highly doubtful this works as you are not using the command modifier to only compare the extension.

ShadowThief
Expert
Posts: 1166
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: batch delete specific file type in subfolders

#5 Post by ShadowThief » 24 Aug 2016 17:36

Squashman wrote:
jaykappy wrote:I am trying to run a command that will search a bunc h of folders and DELETE ALL files EXCEPT a specific file.
I am using this right now.

for %i in (*) do if not %i == .msg del %i

Highly doubtful this works as you are not using the command modifier to only compare the extension.

The file could literally be called .msg

Post Reply