8

Im currently looking for a method to set variables in a windows batch file from linkes in txt document.

So for example, if the text file reads:

http://website1.com
http://website2.com
http://website3.com

I can hopefully output them to variables in the batch. Example:

set var1="Line one of text file, ex: http://website1.com"
set var2="Line two of text file, ex :http://website2.com"
set var3="Line three of text file, ex: http://website3.com"

Any help is appreciated, thanks in advance!

Dustin
  • 6,207
  • 19
  • 61
  • 93
  • As for your problem, I think you are going to find this hard from a bat file. Have you considered powershell, which *may* be easier? Which OS/Version are you actually using? – forsvarir May 04 '11 at 16:19
  • Currently just Windows XP Pro at the moment. And any advice is greatly appreciated. :D – Dustin May 04 '11 at 16:32

3 Answers3

21

Here ya go! Have fun with this one.

(
set /p var1=
set /p var2=
set /p var3=
)<Filename.txt

Lands you with the same results!

Navigatron
  • 416
  • 1
  • 4
  • 12
17

The FOR /F loop command can be used to read lines from a text file:

@echo off
setlocal ENABLEDELAYEDEXPANSION
set vidx=0
for /F "tokens=*" %%A in (sites.txt) do (
    SET /A vidx=!vidx! + 1
    set var!vidx!=%%A
)
set var

You end up with:

var1=http://website1.com
var2=http://website2.com
var3=http://website3.com
Anders
  • 97,548
  • 12
  • 110
  • 164
  • hi Anders, what if i want to take only website addrerss as out put? current output is "var1=http://website1.com" desired out put is "http://website1.com" – Kamlendra Sharma Feb 26 '17 at 05:55
0

Based on @Andres' answer, in case anyone is looking only for the values of the variables as an output:

@echo off
setlocal ENABLEDELAYEDEXPANSION
set vidx=0
for /F "tokens=*" %%A in (sites.txt) do (
    SET /A vidx=!vidx! + 1
    set var!vidx!=%%A
)

for /L %%I in (1,1,%vidx%) do (
echo !var%%I!
)

Pause

output:

http://website1.com
http://website2.com
http://website3.com

Of course this method is only helpful if you want to do some text manipulation or something, but it isn't the parctical way if you just want to print the contents of the text file.

KorkOoO
  • 522
  • 1
  • 4
  • 15