替換多個文件中的文字 - 出現重複錯誤

替換多個文件中的文字 - 出現重複錯誤

我想循環遍歷當前資料夾中的所有文件(本測試為 2 個)並替換文字。

替換工作正常,但我在 file1 中留下了 newfile1 和 newfile2,在文件 2 中留下了相同的內容。

假設我的 ForEach-Object 位於錯誤的位置但無法修復它。有什麼建議麼?

@echo off
call:DoReplace "a1" "a2" *.txt "a3" "a4" 
exit /b

:DoReplace
echo ^(Get-Content "%3"^) ^| ForEach-Object { $_ -replace %1, %2 -replace %4, %5} ^| Set-Content %3>Rep.ps1 
Powershell.exe -executionpolicy ByPass -File Rep.ps1
if exist Rep.ps1 del Rep.ps1
echo Done
pause

答案1

這並不漂亮,但它有效:

Get-ChildItem \\path\to\folder -Filter '*.txt' | foreach {
$text = Get-Content $_.FullName
$text = $text -replace 'a2','test'
$text = $text -replace 'a4','foo'
$text | Set-Content $_.FullName
}

您的腳本的問題是您需要Set-Content循環ForEach-Object

相關內容