vDom
vDom

Reputation: 43

How to recursively delete all files from a given path except files with a certain file extension?

The answers I found on the internet do not work if the directory name has space character e.g. "Camera Roll"

I've tried to play around with the for/dir/findstr command but nothing seems to work

Batch file content:

@echo off
for /f %%F in ('dir c:\Users\melov\Pictures /s/b/a-d ^| findstr  /v ".jpg"') do echo "%%F"
@echo on

Mind you I replaced the DEL command by ECHO just so I can simulate the problem.

"c:\Users\melov\Pictures\desktop.ini"
"c:\Users\melov\Pictures\Camera" **(PROBLEM HERE)**
"c:\Users\melov\Pictures\ControlCenter4\Scan\CCF06182019.pdf"
"c:\Users\melov\Pictures\Saved" **(PROBLEM HERE)**
"c:\Users\melov\Pictures\Screenshots\desktop.ini"
"c:\Users\melov\Pictures\Screenshots\Screenshot"
"c:\Users\melov\Pictures\Screenshots\Screenshot"

Original folder structure

├───Camera Roll
├───ControlCenter4
│   ├───Email
│   ├───OCR
│   ├───Scan
│   └───SharePoint
├───cunha
├───Saved Pictures
└───Screenshots

I want to delete all files except the ".jpg"

Upvotes: 1

Views: 257

Answers (1)

user7818749
user7818749

Reputation:

cmd has a default delimiter which is whitespace, so you simply tell it to change default delimiter.

@echo off
for /f "delims=" %%F in ('dir /b /s /a-d "c:\Users\melov\Pictures " ^| findstr  /v ".jpg"') do echo "%%F"

Similar principal using tokens=*

@echo off
for /f "tokens=*" %%F in ('dir /b /s /a-d "c:\Users\melov\Pictures " ^| findstr  /v ".jpg"') do echo "%%F"

Upvotes: 1

Related Questions