我想在变量行之后的子文件夹中添加一行到一系列cfg文件中。
some text…光。0 =一些文本光。1 =一些文本…光。N =一些文本... 一些文本之前每个文本文件都有不同的n数据线。
所有我想添加的是(n+1)数据行之后的n行在每个子文件夹的cfg文件。
light.(n+1) = some text我想在PowerShell中执行这个任务。
# 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+) =.*?$(?![rn]+^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 $_
}
(*我肯定我在什么地方读到过)
假设"轻"行是连续的,中间没有其他文本块,并且它们是有序的,最大的数字在最后。您可能必须使用正则表达式中的行结尾rn
和替换文本中的' n,以使它们匹配。