我目前正在嘗試遍歷.ini檔案中的每個專案并稍后處理這些值。但我無法弄清楚如何。我的config.ini檔案看起來像這樣:
[items]
item_1=XXXXX
item_2=XXXXX
item_3=XXXXX
item_4=XXXXX
[SomeSection]
......
我找到了一種迭代和回顯config.ini檔案中每個專案的方法,如下所示:
@echo off
for /F %%i in (config.ini) do (
echo %%i
)
我的問題是我想使用特定的值。所以我必須檢查檔案中的類別和鍵config.ini。我嘗試使用它,但遇到了錯誤:
@echo off
for /F %%i in (config.ini) do (
SET item = %%i
if %item%==[items] (
rem do something here with the key and values now
)
)
正如我已經提到的,我無法將值保存到另一個變數,這導致我無法使用它們的問題。
uj5u.com熱心網友回復:
一個非常簡單的方法是提前確定目標節頭的行號,然后在讀取組態檔時跳過諸如許多行,一旦出現另一個括號內的字串就停止:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_CONFIG=%~dp0config.ini" & rem // (path to configuration file)
set "_SECT=items" & rem // (section name without brackets)
rem // Clean up variables whose names begin with `$`:
for /F "delims==" %%V in ('set "$"') do set "%%V="
rem // Gather number of line containing the given section (ignoring case):
for /F "delims=:" %%N in ('findstr /N /I /X /C:"[%_SECT%]" "%_CONFIG%"') do set "SKIP=%%N"
rem // Read configuration file, skipping everything up to the section header:
for /F "usebackq skip=%SKIP% delims=" %%I in ("%_CONFIG%") do (
rem // Leave loop as soon as another section header is reached:
for /F "tokens=1* delims=[]" %%K in ("%%I") do if "[%%K]%%L"=="%%I" goto :NEXT
rem // Do something with the key/value pair, like echoing it:
echo(%%I
rem // Assign a variable named of `$` key and assign the value:
set "$%%I"
)
:NEXT
rem // Return assigned variables:
set "$"
endlocal
exit /B
此腳本將根據您的示例組態檔分配以下變數:
$item_1=XXXXX $item_2=XXXXX $item_3=XXXXX $item_4=XXXXX
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312625.html
上一篇:過濾掉批處理檔案中回圈內的文本
