如何根据正则表达式模式在 Powershell 中的某一行上方和下方添加行?

如何根据正则表达式模式在 Powershell 中的某一行上方和下方添加行?
03,201779,,01354,73923309,,,TEST2,7962753,,,0343,5087632,,/#end of line
04,399,777873,,,,text234,,,,/ 
33,TEST1,,,0343,,93493,,,343,,,,TEST3,,,,,,/
37,TEST37,text
49,24605597,6,343,343,343,,,3434,,,/

我的.txt文件中有5万个部分,从03条记录开始到49条记录结束。

I want to add a record say:- "02, 33, TEST02,,,,022,,,99/  ABOVE all 03 records.
I want to add a record say:- "50, 3434, TEST50,,,034,,,343/  BELOW all 49 records.

此代码不起作用 - 请帮助我 - 这非常非常重要..我需要为一项紧急任务执行此操作。

$FileName = "C:\testdata\file.txt"
$Pattern = "[03,]"
[System.Collections.ArrayList]$file = Get-Content $FileName
$insert = @()

for ($i=0; $i -lt $file.count; $i++) {
  if ($file[$i] -match $pattern) {
    $insert += $i-1 #Record the position of the line before this one
  }
}

#Now loop the recorded array positions and insert the new text
$insert | Sort-Object -Descending | ForEach-Object { $file.insert($_,"02, 33, TEST02,,,,022,,,99/") }

Set-Content $FileName $file

答案1

你可以使用这个代码:

$fileName = "C:\testdata\file.txt"
(Get-Content $fileName) |
    Foreach-Object {
        if ($_.StartsWith("03,")) {
            Write-Output "02, 33, TEST02,,,,022,,,99/"
        }
        Write-Output $_                 # send the current line to output
        if ($_.StartsWith("49,")) {
            Write-Output "50, 3434, TEST50,,,034,,,343/"
        }
    }

相关内容