我正在编写一个用于自定义配置文件的脚本。我想替换此文件中的多个字符串实例,并尝试使用 PowerShell 来完成这项工作。
对于单个替换来说它工作得很好,但是进行多个替换非常慢,因为每次它都必须再次解析整个文件,并且这个文件非常大。该脚本如下所示:
$original_file = 'path\filename.abc'
$destination_file = 'path\filename.abc.new'
(Get-Content $original_file) | Foreach-Object {
$_ -replace 'something1', 'something1new'
} | Set-Content $destination_file
我想要这样的东西,但我不知道如何写:
$original_file = 'path\filename.abc'
$destination_file = 'path\filename.abc.new'
(Get-Content $original_file) | Foreach-Object {
$_ -replace 'something1', 'something1aa'
$_ -replace 'something2', 'something2bb'
$_ -replace 'something3', 'something3cc'
$_ -replace 'something4', 'something4dd'
$_ -replace 'something5', 'something5dsf'
$_ -replace 'something6', 'something6dfsfds'
} | Set-Content $destination_file
最佳答案
一种选择是将-replace
操作链接在一起。每行末尾的 `
转义换行符,导致 PowerShell 继续解析下一行的表达式:
$original_file = 'path\filename.abc'
$destination_file = 'path\filename.abc.new'
(Get-Content $original_file) | Foreach-Object {
$_ -replace 'something1', 'something1aa' `
-replace 'something2', 'something2bb' `
-replace 'something3', 'something3cc' `
-replace 'something4', 'something4dd' `
-replace 'something5', 'something5dsf' `
-replace 'something6', 'something6dfsfds'
} | Set-Content $destination_file
另一种选择是分配一个中间变量:
$x = $_ -replace 'something1', 'something1aa'
$x = $x -replace 'something2', 'something2bb'
...
$x
关于powershell - 如何使用 PowerShell 替换文件中的多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3403217/