如何在最后一个变量数据集

时间:2016-11-03 19:47:50

标签: powershell variables

我想在变量行之后的子文件夹中为一系列cfg文件添加一行。

some text ...
light.0 = some text
light.1 = some text
...
light.n = some text
... some text

每个文本文件都有不同的n th 数据行。

我想要添加的是在子文件夹中的每个cfg文件中的那些n th 行之后的(n + 1) th 数据行。

light.(n+1) = some text

我想在PowerShell中执行此任务。

1 个答案:

答案 0 :(得分:0)

# Get all the config files, and loop over them
Get-ChildItem "d:\test" -Recurse -Include *.cfg | ForEach-Object {

    # Output a progress message
    Write-Host "Processing file: $_"

    # Make a backup copy of the file, forcibly overwriting one if it's there
    Copy-Item -LiteralPath $_ -Destination "$_+.bak" -Force

    # Read the lines in the file
    $Content = Get-Content -LiteralPath $_ -Raw

    # A regex which matches the last "light..." line
    #  - line beginning with light.
    #  - with a number next (capture the number)
    #  - then equals, text up to the end of the line
    #  - newline characters
    #  - not followed by another line beginning with light
    $Regex = '^light.(?<num>\d+) =.*?$(?![\r\n]+^light)'

    # A scriptblock to calculate the regex replacement
    # needs to output the line which was captured
    # and calculat the increased number
    # and output the new line as well
    $ReplacementCalculator = {

        param($RegexMatches)

        $LastLine = $RegexMatches[0].Value
        $Number = [int]$RegexMatches.groups['num'].value

        $NewNumber = $Number + 1

        "$LastLine`nlight.$NewNumber = some new text"

    }

    # Do the replacement and insert the new line
    $Content = [regex]::Replace($Content, $Regex, $ReplacementCalculator, 'Multiline')

    # Update the file with the new content
    $Content | Set-Content -Path $_

}

(*我确定我在某处读过)

假设&#39;灯光&#39;行是连续的,中间没有其他文本块,并且它们是有序的,最高的数字是最后一个。您可能必须使用正则表达式中的行结尾\r\n和替换文本中的`n,以使它们匹配。

(抱歉正则表达式)