Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove line break if line does not start with : with Powershell

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading