Search code examples
batch-filebatch-delete

How to store the split value in variable to subtract from another variable in batch script


I have few zip files in a folder with a number in it's name with underscore like C:\codedeploy\uat-prod\xxxx_123.zip. I would like to iterate through all files and get the number in file name into a variable(fileNumber) to substract it from a another variable(buildNumber)(this is integer value which I am loading from a text file). After first split I am able to get 123.zip(in %%a), So, for getting number from this, I split that again(got this into %%i). Then I tried assigning these values to variable fileNumber, buildNumber and result. I checked it whether these variables are getting assigned values by writing them into a test.txt file with comma separated. but all the variable values are empty. After these values calculated properly I would like to delete the file if it satisfies the this condition if %result% GEQ %limit%.

set /p Build=<release_version.txt
Setlocal EnableDelayedExpansion
set /A result=0
for %%f in (C:\codedeploy\uat-prod\*.zip) do (
echo "fullname: %%f ">>"C:\codedeploy\uat-prod\test.txt"
    for /f "tokens=2 delims=_" %%a in ("%%f") do (
        set limit=7
        echo "FileNum: %%a">>"C:\codedeploy\uat-prod\test.txt"
        for /f "tokens=1,2 delims=." %%i in ("%%a") do (
            echo "Num: %%i">>"C:\codedeploy\uat-prod\test.txt"
            set /A fileNumber=%%i
            set /A buildNumber=%Build%
            set /a result=buildNumber-fileNumber
            echo "fileNumber: %fileNumber%, buildNumber: %buildNumber%, finla: %result%">>"C:\codedeploy\uat-prod\test.txt"
            REM set /a result=%Build%-%%i
            REM echo "value is=%result%"
            REM if %result% GEQ %limit% (Del %%f)
            REM if %result% GEQ %limit% (Del "%%f")
            rem if %Build%-%%i GEQ %limit% (Del /S /Q "%%f")
        )
    )
)

I have been scratching my head to achieve this. So, any help on this would be appreciated. Thanks in advance.


Solution

  • I may not quite have understood what you were trying to achieve, but this looks like it should work the same but more efficiently, (and obviously uses the appropriate !'s for the delayed variable).

    Set /P "Build=" 0< "release_version.txt"
    Set "limit=7"
    Set "result=0"
    (
        For %%G In ("C:\codedeploy\uat-prod\*_*.zip") Do (
            Echo "fullname: %%G"
            For /F "EOL=: Tokens=2 Delims=_" %%H In ("%%~nG") Do (
                Echo "FileNum: %%H%%xG"
                Echo "Num: %%H"
                SetLocal EnableDelayedExpansion
                Set /A result=Build - %%H
                Echo "fileNumber: %%H, buildNumber: %Build%, final: !result!"
                Rem If !result! GEq %limit% Del /A /F "%%G"
                EndLocal
            )
        )
    ) 1> "C:\codedeploy\uat-prod\test.txt"