1
set a=file
if exist "folder\%a%" ( 
 set /p x= < "folder\%a%" 
 echo %x% 
)

i've been writing batch files for a long time, but i don't get it why this code does not work. Im expecting the code to echo out the content of the %a%. but all it returns is the status of ECHO (Echo is ON)

the %a% (file) contains a string ('keyword') which is expected to be echoed out when set in %x%

i even tried to put an extension (.txt) but still it does not work

2 Answers 2

2

It doesn't work, because the complete parenthesis block (and also echo %x%) is evaluated before the "set /p" will be executed, you could change to delayed expansion.

SETLOCAL EnableDelayedExpansion
set a=file
if exist "folder\%a%" ( 
 set /p x= < "folder\%a%" 
 echo !x!
)

[EDIT]

This code also accepts exclamation marks in the filename

set "a=folder\foo!bar.txt"
SETLOCAL EnableDelayedExpansion
if exist "!a!" (
  set /p x= < "!a!"
  echo !x!
)
Sign up to request clarification or add additional context in comments.

9 Comments

may i ask you what does delayed expansion means?
If %a% contains ! (example "foo!bar.txt") then your code breaks
%var% expanded the line or parenthesis block in the moment of reading, before any command of the line or block is executed. The delayed expansion must be enabled and then it expands the !var! like %var%, but in the moment just before excuting each command of a line or block, also "set /?" explains it
@Anders: I changed the code, so it will also work, if %a% contains exclamation marks
haha sorry for making you explain kinda got confused after typing set /? that's why i asked you :P .thanks
|
1
if exist "folder\%a%" ( 
 set /p x=< "folder\%a%"
 SETLOCAL ENABLEDELAYEDEXPANSION&echo !x!&ENDLOCAL
)

This is basically the same code as jeb, but ENABLEDELAYEDEXPANSION will not affect the path, so filenames with ! will still work (% will probably not work, but that is a general problem with batch files and filenames)

set /p x= < .\somefile is a bit of a hack, you might want to consider using FOR /F "tokens=*" %%A ... but FOR will read each line unless you put a if inside the DO. So you end up with something ugly like this if you only want the first line:

set eof=0
for /F "tokens=*" %%A IN ('type "folder\%a%" 2^>nul') DO (
    SETLOCAL ENABLEDELAYEDEXPANSION&(if "!eof!"=="0" (echo.%%A))&ENDLOCAL
    set eof=1
)

1 Comment

A FOR-Loop can be break with a goto :label

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.