简体   繁体   中英

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 eg "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"

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"

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