0

I have a small batch script:

@echo off
cls
setlocal enabledelayedexpansion
SET BINARY_FILES=find_files.cmd;find_files2.cmd
pushd "%cd%"
call :listFiles
popd
goto :eof

:listFiles
    for /R "%cd%" %%i in ( *.cmd ) do (
        set "filen=%%~nxi"
        rem give me only the filename
        call :checkIfIsList !filen!
    )
    goto :eof

:checkIfIsList
    set "FILETOCHECK=%1"
    echo "FILETOCHECK: !FILETOCHECK!"
    echo "Output: %BINARY_FILES:!FILETOCHECK!=%"
    goto :eof

The output of this script is something like this one:

"FILETOCHECK: findstring.cmd"
"Output: find_files.cmd;find_files2.cmd"
"FILETOCHECK: find_files.cmd"
"Output: find_files.cmd;find_files2.cmd"
"FILETOCHECK: find_files2.cmd"
"Output: find_files.cmd;find_files2.cmd"
"FILETOCHECK: first.cmd"
"Output: find_files.cmd;find_files2.cmd"

The problem is: I want, that the second line which starts with "Output: ..." has only this output

 "Output: ;find_files2.cmd"

Why does the string replacement not work?

devopsfun
  • 1,368
  • 2
  • 15
  • 37
  • This management is fully explained at [this answer](http://stackoverflow.com/questions/35532216/cmd-piping-echo-to-set-expanding-variables-in-variables/35538235#35538235): "To solve this problem you must use Delayed Expansion, that is, insert `setlocal EnableDelayedExpansion` command at beginning, enclose the replacement variable in percents, and enclose the original variable in exclamation marks: `echo "Output: !BINARY_FILES:%FILETOCHECK%=!"` – Aacini Mar 06 '16 at 05:45

2 Answers2

2

You have your normal and delayed expansion reversed.

Normal % expansion occurs early within line parsing, and delayed ! expansion occurs at the end. In order for find/replace to work, the find string must be expanded prior to the find/replace operation. So you want

echo "Output: !BINARY_FILES:%FILETOCHECK%=!%"
dbenham
  • 127,446
  • 28
  • 251
  • 390
0

You are using Delayed Expansion, but did not enable it. Add this as first line:

setlocal enabledelayedexpansion
RGuggisberg
  • 4,630
  • 2
  • 18
  • 27
  • This also does not work. In fact, this is part of my script, but I forgot to add it here to stackoverflow. – devopsfun Feb 29 '16 at 13:14