使用 Powershell 根据文本中的其他子字符串更改文本中的多个子字符串

Change multiple substrings in a text based on other substrings in text with Powershell

我们在我们的 ERP 系统中处理 M940 银行对账单,但银行没有在文件中提供对账单编号(它始终显示 00001/00001)所以我想将对账单日期放在对账单编号应该在的位置。每条语句都有一个语句编号,前面是代码 :28C:,一行中的语句日期以 :60F: 开头,如下所示。

:28C:00001/00001
:60F:C220315EUR140379,24
:28C:00001/00001
:60F:C220316EUR440379,24

如何让 Powershell 将 00001/00001 更改为紧随其后的 :60F: 行的日期?在实际情况中,在 :28C: 之前和 :60F: 之后都有代码行,甚至可能还有其他代码。但是,在 :28C: 行之后总会有一个 :60:- 行和日期。

:28C:220315
:60F:C220315EUR140379,24
:28C:220316
:60F:C220316EUR440579,58

我已经创建了一些 powershell 脚本,它添加了其他必要的子字符串并将其移动到一个目录,具体取决于文件中提到的银行账户,但是脚本的那部分与这个问题无关,因此这里没有说明。

我会很高兴 link 将我推向正确的方向。

使用 switch 语句逐行读取文件 (-File) 并使用正则表达式 (regular-expression) 模式匹配 (-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] 使用 -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 变量并输出结果。

  • automatic $_ variable包含手边的输入行,; $_之后输出。