Reputation: 1
I am trying to make a loop by creating a .txt
file and removing numbers from it constantly until the variable in the .txt
file is 0
.
This is how far I got:
@echo off
set /p a=<Name.txt
set /a c=%a%-1
echo %c%> Name.txt
echo %a%
echo %c%
PAUSE
Inside the text file I input a number, for example 8
.
What it is meant to do is take that number and subtract 1
from it then it is meant to memorise it and then overwrite the text file again with a resut of 8 - 1
which is 7
.
So in the text file called Name.txt
I would expect to see 7
but what I see is a blank line. Please help me out with this loop. I was trying to make an invisible code window which would appear and post a message out of nowhere.
Upvotes: 0
Views: 38
Reputation: 34899
The actual problem is the line echo %c%> Name.txt
in case %c
holds a single decimal digit, because such is interpreted as redirection handle together with the >
symbol. Your code should work with respect to that as long as %c%
holds a number consisting of more than one digits.
To solve this problem, there are the following options:
Move the redirection part to the front:
> Name.txt echo %c%
This is the most reliable solution.
Put the redirected command in between parentheses:
(echo %c%) > Name.txt
Insert a SPACE in front of the >
symbol:
echo %c% > Name.txt
Note that the added space becomes part of the output.
Upvotes: 0
Reputation: 79983
In place of
echo %c%> Name.txt
use
>Name.txt echo %c%
Numerics directly before redirectors may cause problems
Upvotes: 3
Reputation: 6032
I'm pretty confused by your code. You are storing the content of name.txt in the variable %a% (set /p a=<Name.txt
). Then you are echoing %c%
into your text file. How is this supposed to work? %c%
is never set in your code. You are also missing the complete part where you are reducing the number by one. Further, you don't have to delete the file and create it again. Simply replace >> with > to overwrite the complete content of the file.
However, this code should do what you need:
@ECHO OFF
SETLOCAL EnableDelayedExpansion
:LOOP
SET /P a=<name.txt
SET /a a=!a!-1
ECHO !a!>name.txt
PAUSE
IF NOT !a!==0 GOTO LOOP
Upvotes: 1