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.
The solution for your problem is to put the "echo"s after the if block is completed. Try this:
This way you can see the solution as you wanted. Cheers! ;]
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.
I used here the construct
echo(
instead ofecho
as this will ensure echoing an empty line even if the variable is empty.If your variable is empty somewhere, it will be the same as having the command "echo" on its own, which will just print the status of echo.
To avoid this, you should replace all your
echo
commands with something like this:That way, if
%var2%
is empty it will just print "echo var2:" instead of "echo off".First create a file a.txt in the same directory u have this batch file ... write some text in that...Note: only Windows 2000 Windows ME Windows XP Windows Vista Windows 7 supports FINDSTR
run this bath file .. you will find a substring(start=5,length=3) of the first line of string you have in a.txt in a newly created file test.txt. Finally got it working !
Not sure, if this post is still read, but nevertheless. You should try the following: On top of the code right after
@echo off
you have to put inAdditionally anywhere you want to use variables changed in a block of brackets (like
For-Loops
orIf's
) you have to change the%
into!
to get!varname!
This should be helping...
Greetings
geisterfurz007