【问题标题】:Powershell to replace text in multiple files stored in many foldersPowershell替换存储在许多文件夹中的多个文件中的文本
【发布时间】:2014-02-28 18:58:30
【问题描述】:

我想替换多个文件和文件夹中的文本。文件夹名称更改,但文件名始终为 config.xml。

$fileName = Get-ChildItem "C:\config\app*\config.xml" -Recurse
(Get-Content $fileName) -replace 'this', 'that' | Set-Content $fileName

当我运行上述脚本时,它可以工作,但它会将整个文本写入 config.xml 中大约 20 次。怎么了?

【问题讨论】:

标签: file powershell replace directory


【解决方案1】:

$filename 是System.IO.FileInfo objects 的集合。 您必须循环获取每个文件的内容: 这应该做你想做的:

$filename | %{
    (gc $_) -replace "THIS","THAT" |Set-Content $_.fullname
}

【讨论】:

  • 注意:这似乎设置了所有文件的内容,即图像文件将作为文本打开并重新保存。我在修改文件之前添加了一个额外的检查
【解决方案2】:

一般来说,您应该使用管道并结合ForEach-Object 和/或Where-Object CmdLets。

在你的情况下,这更像是:

Get-ChildItem "C:\config\app*\config.xml" -Recurse | ForEach-Object -Process {
    (Get-Content $_) -Replace 'this', 'that' | Set-Content $_
}

可以稍微缩短为:

dir "C:\config\app*\config.xml" -recurse |% { (gc $_) -replace 'this', 'that' | (sc $_) }

【讨论】:

  • 不错。感谢您提供简写和简写。
【解决方案3】:

$filename 是一个文件名数组,它试图一次完成所有这些。尝试一次做一个:

$fileNames = Get-ChildItem "C:\config\app*\config.xml" -Recurse |
 select -expand fullname

foreach ($filename in $filenames) 
{
  (  Get-Content $fileName) -replace 'this', 'that' | Set-Content $fileName
}

【讨论】:

  • 如何计算已更改文件的数量和/或所做的更改数量?
【解决方案4】:

我得到了用这种方式替换文本的文件列表。

$filenames = Get-ChildItem|Select-String -Pattern ""|选择文件名

这有 12 个文件。

在所有文件中替换此文本

foreach ($filename in $filesnames){ (Get-Content $filename.Filename) -replace "", ""|Set-Content $filename.Filename }

不要忘记文件名的最后一部分。 $文件名.文件名

【讨论】:

  • $filenames = Get-ChildItem|Select-String -Pattern ""|select 文件名
猜你喜欢
  • 2021-06-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 2015-11-07
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多