简体   繁体   中英

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 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 æ?

Action the replaces in one go and you only need to use Get/Set-Content once:

(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:

$string = 'abcdef'

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

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

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

Write-Output $string

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 $_}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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