[SOLVED] Change multiple substrings in a text based on other substrings in text with Powershell


We process M940 bankstatements in our ERP-system but the bank does not provide the statement number in the file (it always states 00001/00001) so I want to put the statement-date where the statement number should be. Each statement has a statement number preceded with code :28C: and a statement date in a line that starts with :60F: such as below.


How can I get Powershell to change 00001/00001 into the date coming from the :60F: line right after it? In the real thing there are lines with codes before :28C: and after :60F: and maybe even other codes in between. However, there will always be a :60:-line with the date after a :28C: line.


I already have created some powershell script that adds other neccessary substrings and moves it to a directory depending on the bankaccount mentioned in the file but that part of the script is not relevant for this question therefore not stated here.

I would already be very happy with a link that pushes me in the right direction.


Use a switch statement to read from your file line by line (-File) and use regex (regular-expression) pattern matching (-Regex):

switch -Regex -File file.txt {
  '^:28C:'          { $saved = $_; continue } # save the line and continue
  '^:60F:C(\d+)EUR' { $saved -replace '00001/00001', $Matches[1]; $_ }
  default           { $_ } # unrelated line, pass through
  • $saved -replace '00001/00001', $Matches[1] uses the -replace operator to replace verbatim string 00001/00001 with what the (first) capture group ((\d+)) in the branch condition captured (i.e. the amount, composed of one or more (+) digits (\d)), as reflected in the automatic $Matches variable variable and outputs the result.

  • The automatic $_ variable contains the input line at hand, and ; $_ outputs it afterwards.

Answered By – mklement0

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *