Home > database >  Remove line break if line does not start with : with Powershell
Remove line break if line does not start with : with Powershell

Time:03-27

I try to enrich MT940-files. If part of the file looks like this:

:86:Mitsubishi Co Ltd  
1-19, Higashi 88  
MHCBJPJTXXX  
SCN123  
:61:2202280228C211619,64NMSCSWEEP A/C 555603  

I would like it to look like this:

:86:Mitsubishi Co Ltd 1-19, Higashi 88 MHCBJPJTXXX SCN123  
:61:2202280228C211619,64NMSCSWEEP A/C 555603  

So basically join the line with the previous one if it does not start with :

I can get it to remove the line break if it starts with : by using

(Get-Content "filename" -Raw) -replace '\r?\n:' -split '\r?\n' | Set-Content "filename"

but I just cannot get it to remove the line break if it does not start with :.

CodePudding user response:

This should work, likely the regex could be improved though:

(Get-Content path/to/file -Raw) -replace '\r?\n([^:])', ' $1' |
    Set-Content path/to/file

Using the provided text example:

@'
:86:Mitsubishi Co Ltd
1-19, Higashi 88
MHCBJPJTXXX
SCN123
:61:2202280228C211619,64NMSCSWEEP A/C 555603
'@ -replace '\r?\n([^:])', ' $1'

# Results in:
:86:Mitsubishi Co Ltd 1-19, Higashi 88 MHCBJPJTXXX SCN123
:61:2202280228C211619,64NMSCSWEEP A/C 555603

See https://regex101.com/r/S6qIAM/1 for the description.

  • Related