1

我是 Powershell 的新手。我正在尝试对文件中的文本进行多次替换,但我得到了重复的行。我的测试文件有以下几行:

This is a test.
There is a test.

我运行以下脚本:

(Get-Content "C:\temp\test.txt") | 
    foreach-object {

            if ($_ -match "This"){
                $_ -replace "This" , "That"
            }

            if ($_ -match "test"){
                $_ -replace "test" , "toast"
            }

    } | Set-Content "C:\temp\test.txt"

我的输出应该是:

That is a toast.
There is a toast.

但它为输入中第一行的替换输出单独的行:

That is a test.
This is a toast.
There is a toast.

如您所见,在两行之间,第二行仅满足“匹配”条件之一并被正确替换。但是,第一行输出两次——每次替换一个。如果该行同时满足两个条件,我需要脚本仅输出该行一次。

4

2 回答 2

4

很容易为什么你得到 3 行输出。第一个对象是'This is a test'and 匹配第一个if,所以它将替换'This''That'and 输出That is a test。然后,第一个对象也匹配第二个,if因为有 a 'test',所以它也输出'This is a toast'。最后,第二个对象只匹配第二个if,所以它输出'There is a toast'。因此有 3 行输出。

当你键入$_ -replace 'x','y'它返回另一个对象时,它不会改变 $_。如果您正在编写脚本,请继续将其放在多行上并使其按照您的意愿进行。

$file = Get-Content $path
foreach($line in $file){
    if($line -match 'This'){
        $line = $line -replace 'This','That'
    }
    if($line -match 'test'){
        $line = $line -replace 'test','toast'
    }
    $line
}
于 2013-03-22T01:40:14.713 回答
1

我会这样做:

(Get-Content "C:\temp\test.txt") -replace 'This','That' -replace 'test','toast' | Set-Content "C:\temp\test.txt"
于 2013-03-21T15:50:12.277 回答