Powershell - 在单词后的第 14、24、36、46 和 55 个字符后添加字符串

Powershell - add string after 14th 24th 36th 46th and 55th character following a word

我们有许多文件包含以 HDR 开头的 header 行,为了清晰起见需要更新这些行。我是 powershell 编码的新手,想知道如何更新下面的代码来完成这个。
示例:
之前:

HDR,9345561421,20220510,1536838657,20220510,5550810,111003

之后:

HDR, INV-9345561421, DATE-20220510, PO-1536838657, DATE-20220510, ORDER-5550810, CUST-111003
Get-ChildItem 'C:\SFTP\Whirlpool\Invoices\*.csv' | ForEach {
     (Get-Content $_) | ForEach  {          
    $_.Insert(HDR, ,"INV-").Insert(HDR, .........., ,"NVDATE-").Insert(HDR, .........., ........,  ,"PO-").Insert(HDR, .........., ........, ..........,   ,"PODATE-").Insert(HDR, .........., ........, .........., ........,   ,"ORDER-").Insert(HDR, .........., ........, .........., ........, .......,   ,"SHIPTO-")
} | Set-Content $_
}

Santiago Squarzon 提供的以下解决方案非常有效。

$head = 'INV', 'DATE', 'PO', 'DATE', 'ORDER', 'CUST'
foreach($csv in Get-ChildItem 'C:\SFTP\Whirlpool\Invoices\*.csv') {
    $newContent = switch -Regex -File $csv.FullName {
        '^HDR' {
            $i = [ref] 0
            [regex]::Replace($_, ',', { ', ' + $head[$i.Value++] + '-' })
            continue
        }
        Default { $_ }
    }
    Set-Content -LiteralPath $csv.FullName -Value $newContent
}

假设您要替换任何以 HDR 开头的行并且该行具有相同数量的项目 comma-separated(总共 5 个逗号),您可以使用此致电 Replace(String, String, MatchEvaluator):

$head = 'INV', 'DATE', 'PO', 'DATE', 'ORDER', 'CUST'
$line = 'HDR,9345561421,20220510,1536838657,20220510,5550810,111003'
$i = [ref] 0
[regex]::Replace($line, ',', { ', ' + $head[$i.Value++] + '-' })

# Produces this output:
# HDR, INV-9345561421, DATE-20220510, PO-1536838657, DATE-20220510, ORDER-5550810, CUST-111003

您可以将上述逻辑与 switch 结合使用 -File 参数来读取您的文件,并使用 -Regex 参数来定位以 HDR[ 开头的行=25=] (^HDR):

$head = 'INV', 'DATE', 'PO', 'DATE', 'ORDER', 'CUST'
foreach($csv in Get-ChildItem 'C:\SFTP\Whirlpool\Invoices\*.csv') {
    $newContent = switch -Regex -File $csv.FullName {
        '^HDR' {
            $i = [ref] 0
            [regex]::Replace($_, ',', { ', ' + $head[$i.Value++] + '-' })
            continue
        }
        Default { $_ }
    }
    Set-Content -LiteralPath $csv.FullName -Value $newContent
}