简体   繁体   中英

(Batch) How to recursively delete all files/folders in a directory except those with a leading .?

I have a directory, src . I want to recursively delete all of its contents except for files ( .gitignore , ...) and folders ( .git , .vscode , ...) whose names begin with . . Matching that pattern in subdirectories is neither necessary nor harmful.

What is the cleanest way to do this in a batch file?

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"

:: step 1 : delete all files NOT starting "."

FOR /f "tokens=1*delims=" %%a IN (
 'dir /s /b /a-d "%sourcedir%\*" '
 ) DO (
 ECHO %%~nxa|FINDSTR /b /L "." >nul
 IF ERRORLEVEL 1 ECHO(DEL "%%a"
)

:: step 2 : delete all directories NOT starting "."

FOR /f "tokens=1*delims=" %%a IN (
 'dir /s /b /ad "%sourcedir%\*" ^|sort /r'
 ) DO (
 ECHO %%~nxa|FINDSTR /b /L "." >nul
 IF ERRORLEVEL 1 ECHO(RD "%%a"
)
GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

The required DEL commands are merely ECHO ed for testing purposes. After you've verified that the commands are correct , change ECHO(DEL to DEL to actually delete the files.

The required RD commands are merely ECHO ed for testing purposes. After you've verified that the commands are correct , change ECHO(RD to RD to actually delete the directories.

for each filename in the entire subtree, see whether it starts with . , setting errorlevel to non-0 if not and hence delete the file.

Once this has been done, repeat the operation with directorynames, but sort the names found in reverse so that a subdirectoryname of any directory will appear before the directoryname. Attempt to remove the directory with an rd - it will remain if it contains files or subdirectories (which implicitly will start . ). Append 2>nul to the rd line to suppress error messages (where the directory cannot be removed as it still contains files/subdirectories)

Try this to exclude folders with a leading dot (on a per folder base):

for /f "tokens=*eol=." %%A in ('dir /B /AD') do Echo=%%A

This doesn't affect folder names containing dots at other positions.

A relatively slow variant recursing all folders and using findstr to filter all folders containing \\. both chars need escaping with a backslash

for /r /D %%A in (*) do @echo %%A|findstr /V "\\\."

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