需要帮助来创建从* .txt文件读取变量值的批处理文件。
例如,
MyTxtFile.txt
VAR_A=5
VAR_B=10
MyBatFile.bat 需要读取MyTxtFile.txt并回显VAR_A和VAR_B的值
答案 0 :(得分:1)
取决于如何编写这些值。如果您可以在这些值之前添加小的“标签”,则可以轻松完成此工作。
例如,这是我制作的文本文件:
random random
VAR-A 2853
VAR-B 1039410
our code wont notice this text
批处理文件在其上运行并输出:
2853
1039410
代码中的写为:
echo %varA%
echo %varB%
完整代码在这里:
@echo off
cls
cd %~dp0
rem Extracting lines with the tag "VAR-A/B"...
findstr "VAR-A" myfile.txt > Vara.txt
findstr "VAR-B" myfile.txt > Varb.txt
rem Setting the lines to variables...
set /P varA=<Vara.txt
set /P varB=<Varb.txt
rem Deleting temp files...
del Vara.txt
del Varb.txt
rem Now the 2 variables have tags before them, time to remove them...
set varA=%varA:~6%
set varB=%varB:~6%
rem Output:
echo %varA%
echo %varB%
pause>nul
答案 1 :(得分:0)
您可以尝试以下操作(请参阅说明性的rem
注释以了解其工作原理):
@echo off
rem // Define constants here:
set "_FILE=MyTxtFile.txt"
rem // Determine number of lines in text file:
for /F %%C in ('^< "%_FILE%" find /C /V ""') do set "COUNT=%%C"
rem // Read from text file:
< "%_FILE%" (
rem // Loop over number of lines:
for /L %%I in (1,1,%COUNT%) do (
rem // Clear line variable:
set "LINE="
rem // Read current line into variable:
set /P LINE=""
rem // Check whether current line is not empty:
if defined LINE (
rem // Apply current line as variable assignment (avoid messages for invalid ones):
> nul 2>&1 call set "%%LINE%%"
)
)
)
从命令提示符窗口运行批处理文件(我们称其为assign.bat
)。要显示分配的变量,请在提示符下键入set VAR_
:
>>> assign.bat >>> set VAR_ VAR_A=5 VAR_B=10