我們有許多包含以 HDR 開頭的標題行的檔案,為了清晰起見,需要更新這些標題行。我是在 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
}
uj5u.com熱心網友回復:
假設您要替換以HDR開頭的任何行,并且該行具有相同數量的逗號分隔專案(總共 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引數來讀取檔案和使用引數來定位以HDR ( )-Regex開頭的行相結合:^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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474159.html
