INI文件逐行获取部分

时间:2016-06-10 08:27:44

标签: powershell batch-file cmd

我有一个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文件)。

4 个答案:

答案 0 :(得分: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 :(得分:1)

在PowerShell中,您可以使用这两个读取section1的前两行:

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

答案 2 :(得分: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%.

答案 3 :(得分:0)

我建议正确解析INI文件,例如像这样:

public function upload()
{
    if ($this->validate()) {
        $this->imageFile->saveAs('images/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
        return true;
    } else {
        return false;
    }
}

然后您可以像这样访问$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.line1

或者像这样:

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