0

I have a program that reads the file and outputs a random file line number, but when it goes to output it, it just says "Echo is off" Is it possible to fix this? Here is my code:

@echo off
setlocal enabledelayedexpansion
set Counter=1
for /f "tokens=* delims=" %%x in (Lists.txt) do (
  set "Line_!Counter!=%%x"
  set /a Counter+=1
)
set /a Counter=%random% * 100 / 32768 + 1
echo %Counter%
echo "%Line_!Counter!%"
::Just displays echo is off
pause
Behavior
  • 180
  • 11

2 Answers2

1

echo "!Line_%Counter%!" will work. (not very intuitive, but makes sense, if you think about it)

Stephan
  • 53,940
  • 10
  • 58
  • 91
1

There are two problems in your code.

The first has been pointed by Stephan. If you read the answers to this question, you will see that the parser replaces variables referenced with percents before variables referenced with exclamation marks. So when the parsers tries to handle %Line_!Counter!%, !Counter! is still not replaced in the line so %Line_!Counter!% is an undefined variable and is replaced with nothing. The inverse (!Line_%Counter%!) works because when the parser reaches the line, the first substitution is the percent variable and the last the exclamation mark variable.

The second is a logic error. The line

set /a Counter=%random% * 100 / 32768 + 1

will not work as intended if the file has more or less than 100 lines. If it has more, the higher numbered lines will never be selected. If it has less lines, a high numbered non existing line can be selected and as it does no exist, you will again get an echo is off message trying to echo the variable.

@echo off
setlocal enabledelayedexpansion
set Counter=0
for /f "tokens=* delims=" %%x in (Lists.txt) do (
  set /a Counter+=1
  set "Line_!Counter!=%%x"
)
set /a "selected=%random% %% Counter + 1"
echo %selected%
echo "!Line_%selected%!"
pause
Community
  • 1
  • 1
MC ND
  • 69,615
  • 8
  • 84
  • 126
  • No, i want it to be 100 lines because the majority of the files have about one hundred lines – Behavior May 22 '14 at 16:07
  • @Behavior, the posted code selects a line in the range of the readed lines. It adapts to the readed file. If it has more lines, they are considered. If it has less, it selects no more than the number of lines in the file. I was just pointing a possible point of failure. If it is not your case, of course, don't use it. – MC ND May 22 '14 at 16:37
  • @Behavior - No, MC ND is correct. If you fix the random number to between 1 and 100, then you must either guarantee that the file always has at least 100 lines, or else you run the risk of randomly selecting a line that does not exist. Phrases like "majority", "usually", "rarely", "almost always", "almost never" do not help with application development except for perhaps optimization efforts. A well written application must handle all possibilities, even if rare. – dbenham May 22 '14 at 16:40