Search code examples
powershellsplittext-parsing

Split Files in Powershell with Delimiter


I currently have a Powershell script that is iterating through bundled MT103 files. Currently, it checks for a flag and decided to forward the file or not. The problem is that sometimes, MT177 (undesired) information comes bundled with the desired file and the file gets forwarded to the drop point.

How can I modify my Powershell script to detect and split this file based on the delimiter which is '{-'.

An example of this is: Multiple payments are separated by a line break. For example:

{-
MT103 payment 1
-}
{-
MT103 payment 2
-}

The desire is to split this file into multiple files and then process them individually.

The resulting files should contain

{-
MT103 payment 1
-}
{-
MT103 payment 2
-}

Solution

  • This is the code i ended up with:

    $Data = "{- MT103 payment 1 -} {- MT103 payment 2 -}"
    [string[]]$Array = $Data.Split("{")
    if ($Array.Count -gt 1) {
      for ($i = 1; $i -lt $Array.Count; $i++) {
        "{" + $Array[$i] | Out-File $destination-$i.fin
      }
    }
    

    I split the data on the opening brace '{' and then add it back to the resulting string content, then output a reconstructed string with the brace to an output file.

    {- MT103 payment 1 -} 
    {- MT103 payment 2 -}