You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手求助:如何用批处理从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 /f loop grabs the entire line from param.txt into param_line since all your parameters are on a single line.
  • Splitting into pairs: The simple for %%p in (%param_line%) loop automatically splits the line into individual PARAM=value entries (batch uses spaces as default delimiters).
  • Extracting the value: The inner for /f loop uses delims== to split each pair at the equals sign, and tokens=2 tells 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:07:57