Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
I have a text file that has four lines of text as follows:
Hello
Planet
Welcome
GoodbyeI have a batch file that I would like to read in each line and set each line to a variable. For example my batch file is as follows:
set /p hostname=<variables.txt
set /p backupdrive=<variables.txt
set /p backupdir=<variables.txt
set /p xbackupdir=<variables.txtThis does not work because it is only reading in the first line each time, so each variable is:
hostname = Hello
backupdrive = Hello
backupdir = Hello
xbackupdir = HelloI would like it to read:
hostname = Hello
backupdrive = Planet
backupdir = Welcome
xbackupdir = GoodbyeI know I can manually change these variables in the batch file, but I have a bunch of other batch files that have the same variables. And I would like to automate this process and only have the user edit one file (variables.txt).
I have searched for hours and days on this topic but I cannot seem to find anything. If anyone can help, it would greatly be appreciated. Thanks

@echo off
setLocal EnableDelayedExpansionfor /f "tokens=* delims= " %%a in (variables.txt) do (
set /a N+=1
set v!N!=%%a
)
set hostname=!v1!
set backupdrive=!v2!
set backupdir=!v3!
set xbackupdir=!v4!
=====================================
If at first you don't succeed, you're about average.M2

I know this is already solved but I would like to point out that the method you used in your post almost worked.
Instead of inputting the whole text file into each line, input the whole text file into a number of lines by calling a label (or using a second batch file).
call :label<variables.txtgoto otherstuff
:label
set /p hostname=>nul
set /p backupdrive=>nul
set /p backupdir=>nul
set /p xbackupdir=>nul
goto :eof:otherstuff
Just don't forget the "goto :eof" line (the label dosen't have to exist). It won't end the batch, it will only end the call.

Obviously, I mised the point.
=====================================
If at first you don't succeed, you're about average.M2

I don't think you missed the point.
Your solution has the advantage of being more efficient, especially if there is a large number of variables to be set from the text file. With the other method each variable would need it's own set /p line, even if it's not going to be used, in contrast with just using !Vx!.
Your method can even adapt to files with a different number of lines without modification, whilst the other can't, they either match, get lost or don't get set at all. The later is subjectively the worst because the batch would even stop and wait for input from the user, possibly hundreds or even thousands of times.
I was just trying to say it *could* be done that way.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |