powershell - 如何使用 PowerShell 替换文件中的多个字符串

标签 powershell replace

我正在编写一个用于自定义配置文件的脚本。我想替换此文件中的多个字符串实例,并尝试使用 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/

相关文章:

powershell - 使用powershell批量设置变量

powershell - Get-Service 参数绑定(bind)未按预期工作

spring - 可以在 Spring 上下文中使用gradle替换值吗?

php - 如何将我在wordpress帖子上拥有的每个youtube链接转换为嵌入?

java - 如何使用正则表达式替换两个字符串之间的某个字符

powershell - 将凭据从一个 powershell 脚本传递到另一个

用于测试命令是否存在的 PowerShell 习语?

powershell - 从批处理文件运行PS1文件,拇指驱动器上位于同一文件夹

java - 什么等同于 .replaceSecond 或 .replaceThird?

windows - 用不同目录中的文件替换子目录中的多个文件