我有以下脚本:
$allFiles = Get-ChildItem "./" -Recurse | Where { ($_.Extension -eq ".ts")}
foreach($file in $allFiles)
{
# Find and replace the dash cased the contents of the files
(Get-Content $file.PSPath) |
Foreach-Object {$_ -replace "my-project-name", '$appNameDashCased$'} |
Set-Content $file.PSPath
# Find and replace the dash cased the contents of the files
(Get-Content $file.PSPath) |
Foreach-Object {$_ -replace "MyProjectName", '$appNameCamelCased$'} |
Set-Content $file.PSPath
# Find and replace the dash cased the contents of the files
(Get-Content $file.PSPath) |
Foreach-Object {$_ -replace "myProjectName", '$appNamePascalCased$'} |
Set-Content $file.PSPath
}
它获取一个文件并进行一些替换,然后保存该文件。然后它使用相同的文件并进行更多替换,然后再次保存文件。然后它再做一次。
这可行,但似乎效率低下。
有没有办法完成所有替换,然后保存一次文件?
(如果可能的话,我更愿意保持PowerShell的可读风格。)
最佳答案
当然,只需将您的替换链接到 ForEach-Object
block 中:
$allFiles = Get-ChildItem "./" -Recurse | Where { ($_.Extension -eq ".ts")}
foreach($file in $allFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object {
# Find and replace the dash cased the contents of the files
$_ -replace "my-project-name", '$appNameDashCased$' `
-replace "MyProjectName", '$appNameCamelCased$' `
-replace "myProjectName", '$appNamePascalCased$'
} |
Set-Content $file.PSPath
}
关于powershell - 在 PowerShell 中为 -replace 和 Set-Content 组合文件 IO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39111060/