Powershell:使用哈希表替换字符串 [英] Powershell: replacing in strings using a hashtable

查看:73
本文介绍了Powershell:使用哈希表替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我建立了一个哈希表,名称是要替换的东西,键是要替换的东西,像这样:

Okay, so I've set up a hash table with names being what to replace and keys being what to replace with, like this:

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

接下来我该怎么办?我已经尝试过了:

What should I do next? I've 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.

包含test.txt:

Contains of test.txt:

dog
cat
eric

test.txt.out:

test.txt.out:

dog
dog
dog
cat
cat
cat
eric
eric
eric

推荐答案

这里是一种方法:

$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

您看到每行三遍的原因是由于嵌套的foreach循环.对于文件中的每一行,每个哈希表条目都运行一次替换操作.不会更改源文件,但是默认情况下,它会输出替换的结果(即使没有任何更改).

The reason you were seeing each line three times is because of the nested foreach loop. A replace operation was running once per hashtable entry for every line in the file. That doesn't change the source file, but by default it does output the result of the replace (even if nothing is changed).

您可以通过以下方式获得所需的功能:首先将文件读入变量,然后使用循环替换更新该变量.您也不需要文件内容的单独的foreach循环;每个哈希表条目都可以一次通过替换操作来替换全文.

You can get the desired functionality by reading the file into a variable first, and then using your looping replace to update that variable. You also don't need a separate foreach loop for the file contents; the replace can run against the full text in one pass per hashtable entry.

这篇关于Powershell:使用哈希表替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆