Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Batch String Substitution not working when search string is given by a variable

I wipped up some code that's supposed to delete files that don't have names beginning with the value of keep. I'm achieving this by putting the name of the file in tmpL1 and tmpL2 while substituting the value of keep with nothing. If tmpL1 and tmpL2 are different I'm keeping the file, otherwise it gets deleted.

setlocal enabledelayedexpansion
set keep=[File I want to keep]
for /F %%L IN ('dir /b *') do (
    set tmpL1=%%L
    set tmpL2=!tmpL1:%keep%=!
    if !tmpL1!==!tmpL2! (
        echo.[REMOVE]
    ) else (
        echo.[KEEP]
    )
)

This is working fine. However, when I put this code in a larger script, setting tmpL2 suddenly stops working. Instead of (part of) the file name tmpL2 now literally contains tmpL1:=.

Here is the script I want to use it in. The additional for-loops are only for going through a directory tree. The main function of the script is still the same.

setlocal enabledelayedexpansion
for /F %%G in ('dir /b *-snapshots') do (
    set tmpG1=%%G
    for /F %%H in ('dir /b !tmpG1!\*') do (
        set tmpH1=%%H
        for /F %%I in ('dir /b !tmpG1!\!tmpH1!\*') do (
            set tmpI1=%%I
            for /F %%J in ('dir /b !tmpG1!\!tmpH1!\!tmpI1!\*-SNAPSHOT') do (
                set tmpJ1=%%J
                set tmpJ2=!tmpJ1:~0,8!
                for /F %%K in ('dir /b !tmpG1!\!tmpH1!\!tmpI1!\!tmpJ1!\*!tmpJ2!*.pom /O:N') do (
                    set tmp1=%%K
                )
                set keep=!tmp1:.pom=!
                for /F %%L in ('dir /b !tmpG1!\!tmpH1!\!tmpI1!\!tmpJ1!\*!tmpJ2!*') do (
                    set tmpL1=%%L
                    set tmpL2=!tmpL1:%keep%=!
                    pause
                    if !tmpL1!==!tmpL2! (
                        echo.[REMOVE]
                    ) else (
                        echo.[KEEP]
                    )
                )
            )
        )
    )
)

I also tried "lazy" delayed expansion by replacing set tmpL2=!tmpL1:%keep%=! with call set tmpL2=%%tmpL1:%keep%=%%. This also works in the small script, but when I apply it to the big one I get an error like "=%" can't be syntactically processed in this location (that's a free translation since my console is in German).

Anyone have an idea what's causing this?

like image 722
user3249829 Avatar asked Dec 15 '15 13:12

user3249829


1 Answers

You could try to change this line
set tmpL2=!tmpL1:%keep%=!

with

FOR /F "delims=" %%R in (""!keep!"") do set "tmpL2=!tmpL1:%%~R=!"
like image 192
jeb Avatar answered Oct 05 '22 22:10

jeb