为什么这段代码说echo是关闭的? [英] Why this code says echo is off?

查看:973
本文介绍了为什么这段代码说echo是关闭的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段程式码有什么问题?它说 ECHO已关闭

  @ECHO off 
set / p pattern = Enter id:
findstr%pattern%.\a.txt> result
if%errorlevel%== 0(
set var2 =< result
echo%var2%
set var1 =%var2:〜5,3%
echo%var1%> test.txt
echo%var1%
)else(
echo error

del result
pause

解决方案



如Laurent所说,这不是 ECHO 的问题,它是你的代码的问题。



在批处理文件中,块在被执行之前被解析完成。

解析所有的百分比扩展将被完成,所以看起来你的变量不能在块内被改变。



但是由于存在延迟扩展,延迟扩展将在执行时不会在解析块时进行计算。



必须启用,默认情况下禁用延迟展开。

  @ECHO off 
setlocal EnableDelayedExpansion
set / p pattern = Enter id:
findstr%pattern%.\a.txt> result
if%errorlevel%== 0(
set var2 =< result
echo(!var2!
set var1 =!var2:〜5,3!
echo(!var1!> test.txt
echo(!var1!
)else(
echo error

del result

我在这里使用了构造 echo(,而不是 echo ,因为这将确保回显空行,即使变量为空。


What is wrong with this code? It says ECHO is off.

@ECHO off
set /p pattern=Enter id:
findstr %pattern% .\a.txt > result
if %errorlevel%==0 (
set var2= <result
echo %var2%
set var1=%var2:~5,3%
echo %var1% > test.txt
echo %var1%
) else (
echo error
)
del result
pause

Any help is appreciated.

解决方案

As Laurent stated, it's not a problem of the ECHO, it's a problem of your code.

In batch files, blocks are parsed complete before they are executed.
While parsing all percent expansion will be done, so it seems that your variables can't be changed inside a block.

But for this exists the delayed expansion, the delayed expansion will be evaluated in the moment of execution not while parsing the block.

It must be enabled, as per default the delayed expansion is disabled.

@ECHO off
setlocal EnableDelayedExpansion
set /p pattern=Enter id:
findstr %pattern% .\a.txt > result
if %errorlevel%==0 (
  set var2= <result
  echo(!var2!
  set var1=!var2:~5,3!
  echo(!var1! > test.txt
  echo(!var1!
) else (
  echo error
)
del result

I used here the construct echo( instead of echo as this will ensure echoing an empty line even if the variable is empty.

这篇关于为什么这段代码说echo是关闭的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆