majd_wadi
majd_wadi

Reputation: 23

windows batch, setting a variable inside a nested loop

I have the below batch that reads data from a text file, the problem is in the inner loop; it should get the lat created file in the destination folder, and it just gets nothing!

here's my code:

:: Delete Files from folder
@echo off
:: Delete Files from folder
echo y | del "E:\HIS_Data_Consolidation\HIS_Backups\*.bak" 
echo Deleting previous bak files...
set destdir=E:\HIS_Data_Consolidation\HIS_Backups
setlocal
FOR /F "tokens=1,2,3 delims=," %%G IN (clinics.txt) DO (
pushd "%%G"
for /F  "tokens=*" %%a in ('dir *.* /b /a-d /o:e 2^>NUL') do (
set lfile=%%a
)
echo copying "%%G\%lfile%" to "%destdir%" ,,,%%H
copy /y "%%G\%lfile%" "%destdir%
E:
cd "%destdir%
E:\HIS_Data_Consolidation\HIS_Backups\unrar.exe e "%destdir%/%lfile%"
echo y | del "E:\HIS_Data_Consolidation\HIS_Backups\*.rar" 
echo Deleting RAR file...
SET v_test=%lfile%
SET v_result=%v_test:rar=bak%
ren "%v_result%"  "%%I"
echo Ready ...
popd
)
pause

appreciate you help. thanks.

Upvotes: 2

Views: 2855

Answers (2)

ejbytes
ejbytes

Reputation: 183

@npocmaka Thank you! You solved my problem I was working on for hours! I had a similar problem.

I was using a nested for loop and tried to split the for loop into another batch file, but didn't work. So I used 'npocmaka's advice:

This is the batch being called which is inside another for loop.

@ECHO OFF


SET dir=%~1
SET suf=%~2

ECHO IN dir:%dir%
ECHO IN suf:%suf%
PAUSE

SET /A count=1

SETLOCAL EnableDelayedExpansion
pushd %dir%
FOR /R . %%A IN (*.%suf%) DO (

    ECHO File: %%~nxA count:!count!
    PAUSE
    REN %%~nxA !count!.txt
    CALL :increment RESULT count
)
popd
ENDLOCAL


:increment
SET /A count+=1

Upvotes: 0

npocmaka
npocmaka

Reputation: 57252

If you'are using a set inside for body you'll need enabledelayedexpansion: http://www.robvanderwoude.com/variableexpansion.php

edit:

:: Delete Files from folder
@echo off
:: Delete Files from folder
echo y | del "E:\HIS_Data_Consolidation\HIS_Backups\*.bak" 
echo Deleting previous bak files...
set destdir=E:\HIS_Data_Consolidation\HIS_Backups

setlocal enabledelayedexpansion
FOR /F "tokens=1,2,3 delims=," %%G IN (clinics.txt) DO (
    pushd "%%G" 
    for /F  "tokens=*" %%a in ('dir *.* /b /a-d /o:e 2^>NUL') do (
        set lfile=%%a
    )
    echo copying "%%G\!lfile!" to "!destdir!" ,,,%%H
    copy /y "%%G\!lfile!" "!destdir!"
    E:
    cd "!destdir!"
    E:\HIS_Data_Consolidation\HIS_Backups\unrar.exe e "!destdir!/!lfile!"
    echo y | del "E:\HIS_Data_Consolidation\HIS_Backups\*.rar" 
    echo Deleting RAR file...
    SET v_test=!lfile!
    SET v_result=!v_test:rar=bak!
    ren "!v_result!"  "%%I"
    echo Ready ...
    popd
)
endlocal
pause

Upvotes: 2

Related Questions