如何基於正規表示式模式在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 檔案中有 50,000 個部分,從 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/"
        }
    }

相關內容