user2530955
user2530955

Reputation: 1

Creating Batch to keeping one file and deleting the rest when all files have same extension and in same folder

I need to create a batch command that will keep one file from all the same extensions and delete the rest of them.

For example, I have folder called Photograph on desktop. It contains pictures that are all in .png format. However, out of those files I want to keep birds.png and delete the rest of pictures. How can I achieve this?

Upvotes: 0

Views: 227

Answers (3)

foxidrive
foxidrive

Reputation: 41297

Don't run it in any other folder than the one you need it in. :)

@echo off
attrib +h bird.png
del *.png
attrib -h bird.png

Upvotes: 1

Monacraft
Monacraft

Reputation: 6620

Very easy. Use the for /r loop

for /r "Photograph" %%a in (*) do (
if %%~na NEQ [file to keep e.g. bird] del "%%a"
)

Run this from the desktop and it will delete all files put in the folder "Photograph" except for the file name put in the specified place.

I tried this myself and it worked fine. Tell me if you need anything else,

Yours Mona

Alternate

forfiles /p "[pathtofile including file itself]" /c "cme.exe /c if @fname NEQ "bird" del @path"

That should work.

Upvotes: 1

Kristian Oye
Kristian Oye

Reputation: 1202

@echo off

if NOT EXIST %2 (
echo "Usage: allBut.bat <pattern> <filename>
goto:end
)

for %%f in (%1) do (
IF NOT %%f==%2 (
    echo Deleting %%f because it is not %2
    del %%f
)
)

e.g. allBut *.png bird.png

Upvotes: 0

Related Questions