2016-11-03 12 views
-1

可変行の後にサブフォルダ内の一連のcfgファイルに行を追加したいとします。最後の可変データセットの後に設定ファイルに新しい行を追加する方法

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

各テキストファイルは、様々なN 番目のデータ線を有します。

私は追加したいすべてのサブフォルダ内の各CFGファイルのそれらのn 番目の行の後に(N + 1)番目のデータラインです。

light.(n+1) = some text

このタスクをPowerShellで実行したいです。

+2

ようこそ。私たちはスクリプト作成サービスではありません。 [ヘルプ]を開いて、少なくとも[尋ねる]を読んでください。次に、あなたの質問を編集し、[mcve]を提供してください。自分でタスクを解決したところにコードを表示し、タスクを完了できない理由を説明してください。誰かがあなたを助けるでしょう... – JosefZ

答えて

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 $_ 

} 

は、「光」のラインがで、途中で他のテキストの無いブロックと隣接しており、それらが注文されていることを前提と(*私は私がどこかにいることを読んで確信しています)最高数は最後です。正規表現内の行末「\r\n」と置き換えテキストの「n」を合わせて、それらを一致させる必要があるかもしれません。 (正規表現については申し訳ありません)

スタックオーバーフローへ

+0

ライトラインは、上記の質問テキストに記載されているのと同じように、スペースやラインを使わずに連続して1行ずつ連続して連続しています。 'light.1 = some text' ' light .2 =一部text' 'light.3 =一部text' ' light.4 =一部text' 'light.5 =一部text' ' .' '.' ' .' 'light.n = some text' ありがとうございます。 しかし、私はそれが新しい行tp .cfgファイルをサブフォルダに追加することに失敗することがわかります。 – kvari

+0

サブフォルダ内に.bakファイルも作成されません。はい、数字と等号の間に各行にスペースがあります。つまり、light.17 = some text。また、それぞれの.cfgファイルのライトデータグループの上と下のデータ行も、私の上記の元の質問テキスト。 – kvari

+0

サブフォルダのパスにワイルドカード文字がある場合はどうなりますか? Get-ContentとCopy-Itemが '-Path'の代わりに' -LiteralPath'を使うように私の答えを編集しました。 – TessellatingHeckler

関連する問題