1

I'm trying to set a variable to another variable's value with a substring removed. This happens inside a couple of for loops, which I'll illustrate below.

setlocal EnableDelayedExpansion
for %%e in (a b c d) do (
    set outerLoop=%%e

    echo Handling !outerLoop!

    dir *_!outerLoop! /S /B >inner-loop-files.txt
    for /F "tokens=*" %%A in (inner-loop-files.txt) do (
        set innerLoopFile=%%A
        set search=_!outerLoop!

        REM Not working!
        REM set replacedFile=!innerLoopFile:search=!

        echo !innerLoopFile!
        echo !replacedFile!
    )
)

I'm expecting output like this:

Handling a
C:\Directory\File.ext_a
C:\Directory\File.ext

I know the marked line in the innermost loop is close, but I can't quite get the right expansion syntax. When I do this, it works for the single example (though since it's not using a variable, it's wrong for the other iterations):

set replacedFile=!innerLoopFile:_a=!

What do I need to do to this expression for search to expand properly?

set replacedFile=!innerLoopFile:search=!
Dov
  • 15,530
  • 13
  • 76
  • 177
  • 3
    If `outerLoop` variable have the same value of `%%e` replaceable parameter, then you may directly use it: `set replacedFile=!innerLoopFile:_%%e=!`. This type of management is fully explained at [this post](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990). – Aacini Sep 06 '17 at 15:28
  • @Aacini thanks, that does work, but I'd still like to know why it wasn't working with the more expressive variable name – Dov Sep 06 '17 at 15:30
  • 1
    You may use `for %%x in ("!search!") do set replacedFile=!innerLoopFile:%%~x=!`. As I said, the explanations are in the given link... – Aacini Sep 06 '17 at 15:32
  • 1
    In your example, the word search is a string. Not a variable. Regardless of that if you did try to use search as a variable you would need to reference it with delayed expansion. But you can't because you are using delayed expansion with the innerloopfile variable. You can't do double delayed expansion. – Squashman Sep 06 '17 at 15:57
  • In my opinion, the better way to do this would be to isolate the file extension to its own variable. – Squashman Sep 06 '17 at 16:10

0 Answers0