replace string in preceding line with value from next line

Welcome Forums General PowerShell Q&A replace string in preceding line with value from next line

This topic contains 1 reply, has 2 voices, and was last updated by

js
 
Participant
3 months, 3 weeks ago.

  • Author
    Posts
  • #105215

    Participant
    Points: 0
    Rank: Member

    I need to use RegEx to find one string and replace it with a string in the following line.
    Before:
    SBR*P*18*RE******MA~
    NM1*IL*1*DOE*JANE*A***MI*124111111800~
    N3*PO BOX 56~
    After:
    SBR*P*124111111800*RE******MA~
    NM1*IL*1*DOE*JANE*A***MI*124111111800~
    N3*PO BOX 56~

    $configFiles = Get-ChildItem -path "C:\test2\" *.DAT 
    foreach ($file in $configFiles)
    {
        (Get-Content $file.PSPath) |
        Foreach-Object { $_ -replace "SBR\*P\*?*","SBR\*P\*124111111800~} | set-Content $file.PSPath  

    I realize my RexEx is not even close.

    thanks,
    Kevin

  • #105238
    js

    Participant
    Points: 217
    Helping Hand
    Rank: Participant

    http://regex101.com Note that the 2nd argument in -replace doesn't use regex.

    PS C:\users\admin> $a = 'SBR*P*18*RE******MA~'
    PS C:\users\admin> $a -replace 'SBR\*P\*\d\d','SBR*P*124111111800'
    SBR*P*124111111800*RE******MA~

    Oh, it could be any number. Maybe this would help: https://www.apharmony.com/software-sagacity/2014/08/multi-line-regular-expression-replace-in-powershell/

The topic ‘replace string in preceding line with value from next line’ is closed to new replies.