新手求助:如何用批处理从TXT文件提取参数对应的值
Solution for Extracting Parameter Values from TXT in Batch Script
Hey there! I see what's going on with your batch script — right now, you're reading the entire line from param.txt as a single variable, which is why !key1! ends up being the full PARAM1=value1 string instead of just value1. Let's fix that with a couple of adjustments to properly split apart each parameter-value pair.
Working Script to Extract Values into key1, key2, etc.
@echo off setlocal enabledelayedexpansion :: Read the entire line of parameters from the text file set "param_line=" for /f "delims=" %%a in (param.txt) do set "param_line=%%a" :: Loop through each PARAM=value entry (split by spaces) set /a index=1 for %%p in (%param_line%) do ( :: Extract just the value part using the equals sign as a delimiter for /f "tokens=2 delims==" %%v in ("%%p") do ( set "key!index!=%%v" set /a index+=1 ) ) :: Verify the results echo Extracted values: !key1!, !key2!, !key3!, !key4!, !key5!, !key6! echo Total parameters processed: !index! pause endlocal
How This Works
- Reading the full line: The first
for /floop grabs the entire line fromparam.txtintoparam_linesince all your parameters are on a single line. - Splitting into pairs: The simple
for %%p in (%param_line%)loop automatically splits the line into individualPARAM=valueentries (batch uses spaces as default delimiters). - Extracting the value: The inner
for /floop usesdelims==to split each pair at the equals sign, andtokens=2tells it to keep only the part after the equals sign (your desired value). - Assigning to indexed variables: We then store each value in
key1,key2, etc., incrementing the index each time.
Bonus: Directly Create Variables Named After Parameters
If you'd prefer to have variables like !PARAM1!, !PARAM2! instead of indexed keys, you can simplify the script even more:
@echo off setlocal enabledelayedexpansion set "param_line=" for /f "delims=" %%a in (param.txt) do set "param_line=%%a" :: Directly set variables matching the parameter names for %%p in (%param_line%) do set "%%p" echo PARAM1 value: !PARAM1! echo PARAM2 value: !PARAM2! pause endlocal
This works because set "%%p" takes the string PARAM1=value1 and treats it as a variable assignment directly.
内容的提问来源于stack exchange,提问作者Kiwi Rupela
相关产品推荐
相关产品推荐

