7

For example, I can delete all .exe files using the following wildcard:

del *.exe

How can I do the opposite, i.e. delete all files that do not end in .exe?

alexia
  • 14,440
  • 8
  • 42
  • 52

4 Answers4

10

You can try this.

FOR /R [directory] %%F IN (*.*) DO IF NOT "%%~xF" == ".[extension]" DEL /F /S "%%F"

Or, if you have only one .exe file, it’s even simpler.

for %i in (*.*) do if not %i == FILE.EXE del %i
Arseny
  • 5,159
  • 4
  • 21
  • 24
  • I need to learn the harder ways, too (actually, it isn't so hard), so you got the checkmark. :) – alexia Feb 11 '11 at 19:26
  • Thanks. I checked these two solutions in FreeDOS (running in VirtualBox, because my PC runs Linux), and the second one worked (but it’s still for one file). About the first one — it looks like it is only for Windows 2000 and XP. More information is available here: http://www.computerhope.com/forhlp.htm – Arseny Feb 11 '11 at 19:32
4

There's no direct way, here's one scriptless way to do it:

  1. Create a subdirectory.
  2. Copy all *.exe* files to the subdirectory.
  3. Delete all files (*.*) in the current directory.
  4. Copy all files in the subdirectory to the current directory.
  5. Delete all files in the subdirectory.
  6. Remove (rmdir) the subdirectory

And here's the code:

C:\mydir> mkdir temp
C:\mydir> move *.exe temp
C:\mydir> del *.* /f /q
C:\mydir> move temp\*.exe .
C:\mydir> rmdir temp
Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198
tenor
  • 1,095
  • 6
  • 8
2

Don't know if this will work for you (depends on if you have other read-only files on your directory) but this should work:

attrib +R *.exe
del *.*
attrib -R *.exe

Regarding your question, there's no such thing as "excluding" wildcards in DOS default commands

Jcl
  • 27,696
  • 5
  • 61
  • 92
0

To enhance the response of the question (was about excluding wildcards): if you do not search for a specific extension, you can use this for-loop:

for /F "usebackq" %i IN (`dir /b *^|findstr /i /v <PATTERN>`) DO @echo %i

replace "echo" with "del"...

Mayra Delgado
  • 531
  • 4
  • 17