BATCH 输入重定向运算符
set a=file
if exist "folder\%a%" (
set /p x= < "folder\%a%"
echo %x%
)
我已经写批处理文件很长时间了,但我不明白为什么 这段代码不起作用。我期待代码回显内容 %一个%。但它返回的只是 ECHO 的状态(Echo is ON)
%a%(文件)包含一个字符串(“关键字”),预计在以下情况下会回显该字符串: 设置为 %x%
我什至尝试添加扩展名(.txt),但仍然不起作用
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不起作用,因为在执行“set /p”之前会评估完整的括号块(以及 echo %x%),您可以更改为延迟扩展。
[编辑]
此代码还接受文件名中的感叹号
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.
[EDIT]
This code also accepts exclamation marks in the filename
这与 jeb 的代码基本相同,但 ENABLEDELAYEDEXPANSION 不会影响路径,因此文件名带有 !仍然有效(% 可能不起作用,但这是批处理文件和文件名的普遍问题)
set /px=
set /px=
set /px=
set /px=
.\somefile
有点黑客,您可能需要考虑使用FOR /F "tokens=*" %%A
...但是 FOR 将读取每一行,除非您输入a if 在 DO 内。所以如果你只想要第一行,你最终会得到这样丑陋的东西: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 usingFOR /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: