Batch File: How to read only sections in a INI file

若如初见. 提交于 2019-12-02 07:41:43
@ECHO OFF
SETLOCAL
SET INIFile="%~f1"
SET "FLAG="

for /f "usebackq tokens=1,*eol=|delims==" %%a in (%INIFile%) do (
 IF "%%b"=="" (
  REM No "=" so section
  IF /i "%%a"=="[%2]" (SET flag=Y) ELSE (SET "flag=")
 ) ELSE IF defined flag (
  REM data line - only if FLAG is defined
  REM set values defined
  SET "%%a=%%b"
  REM pick particular values
  if /i "%%a"=="Value1" set "Key1=%%b"
  if /i "%%a"=="Value2" set "Key2=%%b"
  if /i "%%a"=="Value3" set "Key3=%%b"
 )

)
SET key
SET val

GOTO :EOF

Here's a way to get your values.

The data in the file is either [section] or name=value so settling delims to = will assign either section-only to %%a or name to %%a and value to %%b.

The flag is only set (defined) after its appropriate section is encountered, and cleared on the next section. Only of it is defined will the assignment take place.

The advantage of the simple set %%a=%%b is that it results in setting whatever values are defined in the section - no changes to the code need to take place if new values are added. Your original version has the advantage of picking particular values and setting only those. You pays your money, you takes your choice.

Note that the /i switch on an if statement makes the comparison case-insensitive.

Nota also the use of set "value=string" which ensures that trailing spaces on a line are not included in the value assigned.


edit : By default, the end of line character is ; so any line starting ; is ignored by for/f. The consequence is that the values for the ;-commented-out section would override the values set for the previous section.

Setting eol to | should cure the problem. It really doesn't matter what eol is set to; it's exactly one character which may not appear anywhere in the INI-file (else that line would appear truncated.)

It is possible, if necessary, to set eol to control-Z but selecting an unused character is easier...

Consequently, a one-line change - the eol parameter is included in the for /f options.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!