Home > Software engineering >  Is there a way to delete a folder that contains only one specific file with batch?
Is there a way to delete a folder that contains only one specific file with batch?

Time:12-03

Need a way to delete a folder (rd/rmdir) if it contains only one specific file within. If there are any other files or subfolders, ignore it. Trying to do so with as little code as possible. Currently, I'm doing this...

If Exist "C:\Folder\SubFolder\filename.txt" Move /Y "C:\Folder\SubFolder\filename.txt" "%TEMP%"
If Not Exist "C:\Folder\SubFolder\*" RD "C:\Folder\SubFolder" /Q /S

However, even though the folder contains no files, the folder is never deleted.

Is this possible within a batch file? Thanx in advance.

CodePudding user response:

you can use find to count the number of files in the directory and then findstr to determine the errorlevel and simply use conditional operator &&

No need to check if the file exists either, you can redirect stderr to nul when the file is not found.

@echo off
Move /Y "C:\Folder\SubFolder\filename.txt" "%TEMP%" 2>nul
(dir /b "C:\Folder\SubFolder\*" | find /C /V "^" | findstr /R "\<0\>") && rd /S /Q "C:\Folder\SubFolder"

Edit

As you mentioned that you now only want to move the file if it is the only file in the directory, a few amendments in the current code sorts that out:

@echo off
set "_dir=C:\Folder\SubFolder"
set "fname=filename.txt"

(dir /b "%_dir%\*" | find /C /V "^" | findstr /R "\<1\>" >nul) && if exist "%_dir%\%fname%" (
   move /Y "%_dir%\%fname%" "%temp%"
   rd /S /Q "%_dir%"
)

This time, we check to see if there is only 1 item (file or dir) in the folder, if it is, we test to see if it is filename.txt if not, then we will skip the code block, if it is, move the file and remove the directory.

I created variables for you as _dir and fname that way you only update those two fields instead of all over the code.

  • Related