-3

I would like to send a number to file.txt as a temporary storage for another variable, which can easily be done. I just can't work out what to use to extract the first line of file.txt (which is a number ranging 1-100000) and set it as a %variable% in my running batch script.

So by the end of it I should be able to do echo %first-line-of-file.txt% and it'll print x

Any ideas on how to make this work is much appreciated

TTT
  • 97
  • 2
  • 5

2 Answers2

1

It is simple really.

@echo off
For /f %%i in (file.txt) do set "var=%%i" & Goto :print
:print
Echo %var%

The for loop will typically loop through the entire file. But we do goto :EOF once the first line has been set to exit the loop.

For more help on a for loop. Open cmd.exe and type `for /?

Gerhard
  • 22,678
  • 7
  • 27
  • 43
  • I wish it really was that simple, but when I have any comments after the final echo there, batch tries to execute them all as well.... – Alkanshel Jul 11 '19 at 22:01
  • @Amalgovinus How are your comments constructed? – Gerhard Jul 16 '19 at 06:28
  • Using setlocal enabledelayedexpansion, both double-colon (and rem comments too) are getting executed as commands with their double-colon excluded. Actually this is happening even without the :print, my bad. But it's really weird. Windows 10 – Alkanshel Jul 16 '19 at 18:36
  • @Amalgovinus Does not sound right. I would need to actually see it to find what is wrong. – Gerhard Jul 17 '19 at 12:59
1

a for loop (like Gerhard showed it) is the most general approach (use "delims=" to get the complete line, even if it contains spaces or other delimiters), but to get the first (or only) line of a text file, there is a simpler method:

<filename.txt set /p line=
echo %line%
Stephan
  • 53,940
  • 10
  • 58
  • 91