[英]Powershell to replace text in multiple files stored in many folders
我想替換多個文件和文件夾中的文本。 文件夾名稱更改,但文件名始終為 config.xml。
$fileName = Get-ChildItem "C:\config\app*\config.xml" -Recurse
(Get-Content $fileName) -replace 'this', 'that' | Set-Content $fileName
當我運行上面的腳本時,它可以工作,但它將整個文本寫入 config.xml 大約 20 次。 怎么了?
$filename 是System.IO.FileInfo objects
的集合。 你必須循環獲取每個文件的內容:這應該做你想做的:
$filename | %{
(gc $_) -replace "THIS","THAT" |Set-Content $_.fullname
}
$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
}
通常,您應該使用管道並結合ForEach-Object
和/或Where-Object
CmdLet。
在您的情況下,這更類似於:
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 $_) }
我得到了以這種方式替換文本的文件列表。
$filenames = Get-ChildItem|Select-String -Pattern ""|選擇文件名
這將獲得 12 個文件。
在所有文件中替換此文本
foreach ($filesnames 中的 $filename){ (Get-Content $filename.Filename) -replace "", ""|Set-Content $filename.Filename }
不要忘記文件名的最后一部分。 $文件名.文件名
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.