BATCH 输入重定向运算符

发布于 2024-10-11 11:39:40 字数 294 浏览 5 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谎言月老 2024-10-18 11:39:40

它不起作用,因为在执行“set /p”之前会评估完整的括号块(以及 echo %x%),您可以更改为延迟扩展。

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

[编辑]

此代码还接受文件名中的感叹号

set "a=folder\foo!bar.txt"
SETLOCAL EnableDelayedExpansion
if exist "!a!" (
  set /p x= < "!a!"
  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.

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!
)
扛刀软妹 2024-10-18 11:39:40
if exist "folder\%a%" ( 
 set /p x=< "folder\%a%"
 SETLOCAL ENABLEDELAYEDEXPANSION&echo !x!&ENDLOCAL
)

这与 jeb 的代码基本相同,但 ENABLEDELAYEDEXPANSION 不会影响路径,因此文件名带有 !仍然有效(% 可能不起作用,但这是批处理文件和文件名的普遍问题)

set /px= set /px= set /px= set /px= .\somefile 有点黑客,您可能需要考虑使用 FOR /F "tokens=*" %%A ...但是 FOR 将读取每一行,除非您输入a if 在 DO 内。所以如果你只想要第一行,你最终会得到这样丑陋的东西:

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
)
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
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文