简体   繁体   中英

How to set variables in a Windows batch file from a txt document

Contents of Txt file:

OPS OPS lastmth Jun 2015
OPS OPS currmth Jul 2015

I would like have variables set as:

var1=OPS
var2=OPS
var3=lastmth
var4=Jun 2015 

Is there a way in Windows Batch script to set variables like this?

I. This is to have var1 to var4 available per line (assuming the text file is called Txt_file.txt ):

@echo off
set /A line=0
setlocal enabledelayedexpansion
for /F "tokens=1-3*" %%I in (Txt_file.txt) do (
set /A line+=1
set var1=%%I
set var2=%%J
set var3=%%K
set var4=%%L
rem at this point you have 'var1' to 'var4':
echo LINE !line!:
echo var1: !var1!
echo var2: !var2!
echo var3: !var3!
echo var4: !var4!
)
endlocal

At the rem line the variables are available. Expand them like !var1! rather than %var1% due to delayed expansion (see setlocal /? and endlocal /? for more information on that), because we are in the body of the for /F loop, means in between the parenthesis after do () .
The line counter line is just there for illustration purposes.

Outside of the for /F loop, the variables contain the content of the last line of the text file.
Beyond the setlocal / endlocal block, the variables are no longer available.

So the output will be:

LINE 1:
var1: OPS
var2: OPS
var3: lastmth
var4: Jun 2015
LINE 2:
var1: OPS
var2: OPS
var3: currmth
var4: Jul 2015

II. This is to have var1 , var2 and so on throughout the entire text file (up to var8 in your example):

@echo off
set /A cnt=0
setlocal enabledelayedexpansion
for /F "tokens=1-3*" %%I in (Txt_file.txt) do (
set /A cnt+=1 & set var!cnt!=%%I
set /A cnt+=1 & set var!cnt!=%%J
set /A cnt+=1 & set var!cnt!=%%K
set /A cnt+=1 & set var!cnt!=%%L
)
rem at this point you have !var1!, !var2!, etc.:
echo ALL CONTENT:
for /L %%I in (1,1,%cnt%) do (
echo var%%I: !var%%I!
)
endlocal & set cnt=%cnt%
echo TOTAL AMOUNT: %cnt%

Again at the rem line the variables are available. This time I expand them by a for /L loop because the text file length (number of lines) could differ; the number of entries and thus the amount variables is stored in %cnt% (so you can expand the last variable by !var%cnt%! , means var8 in our situation). You can of course expand the variables like !var1! , etc. instead of the for /L loop; this time also %var1% , etc. works because we are not in the body of the for /F loop. Delayed expansion is required though in order to build up the variables dynamically.

Besides %cnt% , the variables are no longer available beyond the setlocal / endlocal block.

The output will be:

ALL CONTENT:
var1: OPS
var2: OPS
var3: lastmth
var4: Jun 2015
var5: OPS
var6: OPS
var7: currmth
var8: Jul 2015
TOTAL AMOUNT: 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM