Loop to check if folder is empty and rename

April 3, 2011 at 00:25:10
Specs: Windows 7
Hi all,

I am writing to write a simple batch program to loop through the non-empty folders in a directory and rename them. The original folder names and the new name to rename to is provided from a text file named "file.txt"

Example
002,009
003,010
004,011

I have came up with this code so far

@ECHO OFF
:Start
cls
echo 1. Perform run
echo 2. Quit
echo.
set /p choice=Pease make a selection:
if %choice%==1 goto read
if %choice%==2 exit

:read
cls
FOR /F "tokens=1-2 delims=," %%I IN (file.txt) DO (
@echo %%I - %%J
IF EXIST %%I\NUL ECHO FOUND
)

Can anyone guide me on how to check if %I is empty and proceed to rename them to %J ? Any advice will be appreciated. Thank you


See More: Loop to check if folder is empty and rename

Report •


#1
April 3, 2011 at 02:30:25
you can do this easily with a programming language. eg Ruby. If you have a choice, here's a Ruby for Windows script

File.open("file").each do |dir|
    source , destination = dir.split(",")
    source.strip! ; destination.strip!  #get rid of any spaces
    if Dir.exists?(source) #check if source exists
        entries = Dir.glob("#{source}/**/*")
        if entries.size > 0  # if there are files in directory
            File.rename(source , destination ) #rename
        end
    end
end


Report •

#2
April 3, 2011 at 14:06:21
Can anyone guide me on how to check if %I is empty and proceed to rename them to %J ? Any advice will be appreciated. Thank you----

So, Basically are you trying to rename all empty directories ? if thats the case then i would be (in the for loop)
I) run the Remove_Directory (RD) command,If command successful means the folder was empty. ( RD foldername) deletes the folder only if that is empty.
2) execute If exist %%i echo Folder was not empty.
3) if not exist %%i md %%j

How about that ?

Subhash Chandra.


Report •

#3
April 4, 2011 at 08:28:25
Thanks Kurumi and Chandra. I not exactly using ruby nor removing any folders.

I managed to find the solution in computing.net forum

FOR /F "tokens=1-2 delims=," %%I IN (file.txt) DO (
IF EXIST %%I\NUL (
dir /b/a-d %%I > nul 2> nul
if not errorlevel 1 (
ren %%I %%J
)
)

It works but I do not know what dir /b/a-d %%I > nul 2> nul exactly does.
)


Report •

Related Solutions

#4
April 5, 2011 at 12:39:12
i think you should ask in the same thread where you find that answer..

it redirects the output to NUL device so there wont be any output on screen, the result is based on errorlevel

Subhash Chandra.


Report •


Ask Question