2

Suppose there's a text file:

abc %x%
def %y%

and a batch file:

setlocal
set x=123
set y=456
for /f %%i in (textfile.txt) do echo %%i

The output will be

abc %x%
def %y%

Is there any (simple) way to get this (without powershell or special executables)?

abc 123
def 456
jmucchiello
  • 18,754
  • 7
  • 41
  • 61

2 Answers2

2

There is a simpler way with the call

@Echo off
set x=123
set y=456
for /f "delims=" %%i in (textfile.txt) do call call echo %%i

A double call is only necessray if there are double percent signs surrounding the var. But they do harm only if you use double percent signs to halt expansion one level.

  • my actual solution used "call set" as my actual goal was never to echo the data. I never did try "for...do call call". – jmucchiello Dec 10 '16 at 06:18
  • 1
    Why two CALLs? A single CALL will do – dbenham Dec 11 '16 at 16:07
  • @dbenham no, did you test it? I did. –  Dec 11 '16 at 16:15
  • Yes, I have confirmed that it works as I expected. I took your exact code, removed one CALL, and it continued to work. – dbenham Dec 11 '16 at 16:26
  • @dbenham Strange, that is opposed to my above added sample. What Windows do you use? –  Dec 11 '16 at 16:54
  • 1
    @LotPings Even for Win10 your described behaviour would be very unexpected, as a `CALL` [restarts the parser at the perecent expansion phase](http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/4095133#4095133). – jeb Dec 11 '16 at 20:17
  • @dbenham,Jeb I have to apologize, I had temporarly doubled the percent signs in the file and forgot about that. So that doubled percent required forced double expansion. –  Dec 11 '16 at 20:33
1

You can use an extra level of calling to evaluate the text string as follows:

@echo off
setlocal
set x=123
set y=456
for /f "delims=" %%i in (textfile.txt) do call :evalecho %%i
endlocal
goto :eof

:evalecho
    echo %*
    goto :eof

The output of that for you input file is, as requested:

abc 123
def 456
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Took me some time to remember that you can force a second evaluation with stacked pseudo calls. –  Dec 10 '16 at 03:20
  • I picked this answer because it was first and I never knew about the "call :label" syntax so it was also additionally educational. – jmucchiello Dec 10 '16 at 06:19