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,,,/
Hay 50 mil secciones que comienzan en el registro 03 y terminan en el registro 49 en mi archivo .txt.
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.
Este código no funciona. Por favor ayúdenme. Esto es muy, muy importante. Necesito hacer esto para una tarea urgente.
$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
Respuesta1
Podrías usar este código:
$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/"
}
}