简体   繁体   English

如何在Powershell中有效地执行多个替换命令

[英]How to efficiently make multiple -replace commands in powershell

I can see myself that it's stupid to use the get-content command multiple times, does anyone know how to make this more efficient? 我发现自己多次使用get-content命令很愚蠢,有人知道如何提高效率吗?

(Get-Content hvor_har_vi_vaeret_i_aar.html) -replace '"', '"' | set- 
content hvor_har_vi_vaeret_i_aar.html
(Get-Content hvor_har_vi_vaeret_i_aar.html) -replace 'ae', 'æ' | set-content 
hvor_har_vi_vaeret_i_aar.html
(Get-Content hvor_har_vi_vaeret_i_aar.html) -replace 'o/', 'ø' | set-content 
hvor_har_vi_vaeret_i_aar.html
(Get-Content hvor_har_vi_vaeret_i_aar.html) -replace 'aa', 'å' | set-content 
hvor_har_vi_vaeret_i_aar.html

I hope I explained this well enough, if there was something you didn't understand then just write, then I'll try to clarify. 我希望我已经对此进行了充分的解释,如果您不了解某些内容,然后再写,那么我会尽力澄清。

BTW does anyone know how to make it case sensetive, like AE=Æ and not æ? 顺便说一句,有谁知道如何使其区分大小写,例如AE =Æ而不是æ?

Action the replaces in one go and you only need to use Get/Set-Content once: 一口气执行替换操作,您只需使用一次Get/Set-Content

(Get-Content hvor_har_vi_vaeret_i_aar.html) -replace '"','"' -replace 'ae','æ' -replace 'o/','ø' -replace 'aa', 'å' | Set-Content hvor_har_vi_vaeret_i_aar.html

Same but using backtick to split command over multiple lines to make it a bit more readable: 相同,但使用反引号将命令拆分为多行,以使其更具可读性:

(Get-Content hvor_har_vi_vaeret_i_aar.html) `
    -replace '"','"' `
    -replace 'ae','æ' `
    -replace 'o/','ø' `
    -replace 'aa', 'å' |
    Set-Content hvor_har_vi_vaeret_i_aar.html

Another method you can use, which personally I prefer because it very easily allows you to pass these as parameters into a function, is to declare a 2D array and loop through it: 您可以使用的另一种方法是声明2D数组并循环遍历:我个人更喜欢这种方法,因为它很容易使您可以将这些参数作为参数传递给函数。

$string = 'abcdef'

$replaceArray = @(
                 @('a','1'),
                 @('b','2'),
                 @('c','3')
                )

# =============

$replaceArray | 
    ForEach-Object {
        $string = $string -replace $_[0],$_[1]
    }

Write-Output $string

123def 123def

It's even easier if you only want to remove items from your string, because you can do something like this: 'a','b','c' | % {$string = $string -replace $_} 如果您只想从字符串中删除项目,则更加容易,因为您可以执行以下操作: 'a','b','c' | % {$string = $string -replace $_} 'a','b','c' | % {$string = $string -replace $_}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM