1

Making batch which generate previews (everything is fine with this part of code) and also rename files deleting everything after "_" in filename. For example ABAB_abab.png > ABAB.png My code does not see a variable yy in the string: set zz=!xx:yy=! Perceives it like just two letters yy, not a variable. How to fix that?

Here is the script

setlocal enabledelayedexpansion

    for %%a in ("*.png") do (
    set xx=%%~na
    set yy=_!xx:*_=!
    set zz=!xx:yy=!
    
    echo xx= !xx! @rem (okay, returns ABAB_abab)
    echo yy= !yy! @rem (okay, returns _abab)
    echo zz= !zz! @rem (wrong, returns ABAB_abab without any substitutions)
    pause
    )
endlocal

Thank you for help

Pavel_dp
  • 13
  • 2
  • 1
    It is because `yy` in the xpression `set zz=!xx:yy=!` is taken as a literal string but not a variable reference. Something like `set zz=!xx:!yy!=!` cannot work, because this would try to read variables `!xx:!` and `!=!`. But you can put `!yy!` into a `for` meta-variable, which can be nested within `!!`: `for %%y in ("!yy!") do set "zz=!xx:_%%~y=!"` (note that I also included the leading `_` in the search string since you want ot removed). Take a look at this related thread: [Arrays, linked lists and other data structures in cmd.exe (batch) script](https://stackoverflow.com/q/10166386)… – aschipfl Mar 19 '21 at 13:48
  • Thank your explanation. I put this part: [code] for %%y in ("!yy!") do set "zz=!xx:_%%~y=!" [code] and now it see the variable yy. Bud lost a variable xx. So result is xx:__abab. What else I can change? – Pavel_dp Mar 19 '21 at 14:23
  • Oh, I think I oversaw the fact that you already placed the leading `_` to the assignment of `yy`, so it should read `set "zz=!xx:%%~y=!"`. However, this does (still) not touch the variable `xx`. Anyway, you could even simplify the approach: `for %%y in ("_!xx:*_=!") do set "zz=!xx:%%~y=!"` (there is no more variable `yy`)… – aschipfl Mar 19 '21 at 18:37

1 Answers1

0

Here's a quick example to show you a method of achieving another layer of expansion:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

For %%G In ("*.png") Do (
    Set "xx=%%~nG"
    SetLocal EnableDelayedExpansion
    Set "yy=_!xx:*_=!"
    For %%H In ("!yy!") Do Set "zz=!xx:%%~H=!"
    Echo xx = "!xx!"
    Echo yy = "!yy!"
    Echo zz = "!zz!"
    EndLocal
    Pause
)

The doublequotes are included in the Echo commands only for better visualization should there be any spaces in your strings, they're not needed for any other purpose.

Please note, that this will not achieve your intention with any .png files whose basename begins with one or more underscores, _.

Compo
  • 36,585
  • 5
  • 27
  • 39