2016-06-10 45 views
2

剖面线我有一个ini文件是这样的:INI文件度日线

[section1] 
line1 
line2 
[section2] 
line3 
line4

我想读行,但只能从[section1]例如。 我只需要line1line2作为字符串。 现在它正在运行:

SET var=lines.txt 
FOR /F "tokens=*" %%a in (%var%) DO (
    CALL script.cmd %%a 
) 

这是一个批处理文件,但我不能找到一个解决方案。 每当我想使用section2的内容时,我需要使用lines2.txt,但现在我合并在一起(ini上面的文件)。

回答

1

使用标志来切换操作(设置标志时起始头被发现,取消它,当一个报头开始):

@echo off 
set var=test.ini 
set "flag=" 
FOR /F "tokens=*" %%a in (%var%) DO (
    if defined flag (
    echo %%a|find "[" >null && set "flag=" || (
     echo calling script.cmd with parameter %%a 
    ) 
) else (
    if "%%a" == "[section1]" set flag=1 
) 
) 
1

在PowerShell中,你可以使用该两个读头两行从section1

$content = Get-Content "Your_Path_here" 
$section1Start = $content | Where-Object { $_ -match '\[section1\]'} | select -ExpandProperty ReadCount 
$content | Select -Skip $section1Start -First 2 
+1

如果您不知道本节中有多少个键,该怎么办? – Stephan

+0

然后,您必须确定新部分的位置(与section1start相同),减去section1start和section1end,并将其传递给'-first'参数。 –

0

如果你的ini文件的格式有效的,这将设置在所期望部分的所有行的开始[section1]变量列表。它也会处理注释,并会在行上执行左修剪。仅使用cmd内部命令,所以应该很快。

@echo off 

setlocal EnableDelayedExpansion 
set "file=test.ini" 
set "section=[section1]" 

set flag=0 
for /f "usebackq delims=" %%# in ("%file%") do (
    set line=%%# 
    ::trim 
    for /f "tokens=* delims= " %%a in ("!line!") do set "line=%%a" 
    set f=!line:~0,1! 
    if "!f!" neq ";" (
     if !flag! equ 1 (
      for /f "tokens=1* delims==" %%a in ("!line!") do (
      ::for /f "tokens=1* delims==" %%a in ("%%#") do (
       set "!section!.%%a=%%b" 
      ) 
     ) 

     if "!f!" equ "[" (
      if "!line!" equ "%section%" (
       set flag=1 
      ) else (
       set flag=0 
      ) 
     )  
    ) 
) 

set %section%. 
0

我会推荐正确解析INI文件,例如,是这样的:(用点号)

$ini['section1']['line1'] 

或类似这样的:

$inifile = 'C:\path\to\your.ini' 
$ini = @{} 

Get-Content $inifile | ForEach-Object { 
    $_.Trim() 
} | Where-Object { 
    $_ -notmatch '^(;|$)' 
} | ForEach-Object { 
    if ($_ -match '^\[.*\]$') { 
    $section = $_ -replace '\[|\]' 
    $ini[$section] = @{} 
    } else { 
    $key, $value = $_ -split '\s*=\s*', 2 
    $ini[$section][$key] = $value 
    } 
} 

然后你就可以访问section1元素这样

$ini.section1.line1 

您还可以枚举所有这样的部分的元素:

$ini['section1'].Keys 
$ini['section1'].Values 

或如下所示:

$ini['section1'].GetEnumerator()