gpt4 book ai didi

powershell - 在 PowerShell 中为 -replace 和 Set-Content 组合文件 IO

转载 作者:行者123 更新时间:2023-12-01 10:33:32 25 4
gpt4 key购买 nike

我有以下脚本:

$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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com