I have .cfg files each named the same, in many sub-folders, having the following structures :
--some text light.0 = some text light.1 = some text light.2 = some text ... light.n = some text ...some text
I want to add a (n+1)th data line following the last (n)th line of each .cfg file :
light.(n+1) = sonme text
Each .cfg may have varied last (n)th lines.
I tried the following code, yet it seems like it is of no avail so far :
# 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.(?\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 $_ }