2

I have following code snippet

    setlocal enableextensions enabledelayedexpansion
    set b=123
    for %%f in (.\input\*.mgc) do (
       set "b=%%~nf"
       echo %b%
    )

I am expecting it to output file name with no extension but I always get "123". I concluded it has something with late expansion but not quite sure where the problem comes from. I have also tried with echo !b! but in that situation it outputs only "!b!"

3
  • 2
    A common misunderstanding as to how cmd.exe expands the value of the variable. You need to reference the variable as echo !b! Commented Dec 9, 2016 at 18:34
  • @Squashman I wrote in my question that I have tried that but with no results Commented Dec 9, 2016 at 18:38
  • 2
    There are only two ways that echo !b! displays a literal !b! - either you didn't use setlocal enabledelayedexpansion or the one file in the input directory is called !b!.mgc. Those are literally the only two ways your output is possible. If b wasn't being set and delayed expansion was actually on like you claim it is, you'd see the error ECHO is off. Commented Dec 9, 2016 at 20:02

2 Answers 2

2

Try replacing %b% with !b! as explained here:

The variable whose expansion should be delayed should be surrounded by exclamation marks instead of percent signs.

 setlocal enableextensions enabledelayedexpansion
 set b=123
 for %%f in (.\input\*.mgc) do (
     set "b=%%~nf"
     echo !b!
 )
Sign up to request clarification or add additional context in comments.

2 Comments

Apparently I didn't read the entire question, but this works fine for me in Windows 10.
You just posted exactly the same code I used in my question yet said my code did not work in Windows 10 for you.
1

I believe in hard evidence. I can't see you execute the code or if you are obfuscating the code at all so here is me executing your code. It works just like I said.

C:\BatchFiles\SO>type testing.bat
@echo off
setlocal enableextensions enabledelayedexpansion
set b=123
for %%f in (.\input\*.mgc) do (
        echo %%~nf
        set "b=%%~nf"
        echo !b!
)
pause
C:\BatchFiles\SO>dir /b .\input\*.mgc
testfile.mgc

C:\BatchFiles\SO>testing.bat
testfile
testfile
Press any key to continue . . .

C:\BatchFiles\SO>

1 Comment

What OS are you using?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.