PowerShell: replacing strings with hash tables

OK, so I set up a hash table whose name is to be replaced and the key is to be replaced, as shown below:

$r = @{
    "dog" = "canine";
    "cat" = "feline";
    "eric" = "eric cartman"
}

What should I do next? I tried this:

(Get-Content C:\scripts\test.txt) | Foreach-Object {
    foreach ( $e in $r.GetEnumerator() ) {
        $_ -replace $e.Name,$e.Value
    }
} | Set-Content C:\scripts\test.txt.out

But it doesn't work at all. It just writes each line three times without replacing anything

Edit: including test txt:

dog
cat
eric

test. txt. out:

dog
dog
dog
cat
cat
cat
eric
eric
eric

Solution

This is a method:

$file = Get-Content C:\scripts\test.txt
foreach ($e in $r) {
  $file = $file -replace $e.Name,$e.Value
}
Set-Content -Path C:\scripts\test.txt.out -Value $file

The reason you see each line three times is due to the nested foreach loop For each row in the file, a replace operation is run for each hash table entry This does not change the source file, but by default it outputs the result of the replacement (even if it has not changed)

You can read the file into a variable and then update the variable with circular replacement to obtain the required function You also don't need a separate foreach loop for the file content; In one pass of each hash table entry, the replacement can be run against the full text

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>