【问题标题】:Replacing text in files recursively using windows使用Windows递归替换文件中的文本
【发布时间】:2023-01-17 03:30:41
【问题描述】:
所以我可以像这样更改文件中的文本:
(gc file.name) -replace 'Foo', 'Bar' | sc file.name
现在我想为此目录中的每个文件执行此操作。在 DOS 中我会这样做:
for %f in (*.*) do (gc %f) -replace 'Foo', 'Bar' | sc %f
我收到一条有用的消息,告诉我语法错误,但没有告诉我正确的语法是什么。我敢打赌这里有人可以。
【问题讨论】:
标签:
powershell
replace
foreach
dos
【解决方案1】:
您只需要 Get-ChildItem 即可获取目录中的文件和您选择的循环,在本例中为 ForEach-Object。
Get-ChildItem path o argetDirectory -File | ForEach-Object {
(Get-Content -LiteralPath $_.FullName -Raw) -replace 'Foo', 'Bar' |
Set-Content $_.FullName
}
如果你想这样做递归地对于targetDirectory 下的所有文件,您只需包含-Recurse。
【解决方案2】:
我用了:
foreach ($F in dir){ (gc $F) -replace 'Foo', 'Bar' | sc $F }