How to escape a backslash in Powershell

前端 未结 2 1461
Happy的楠姐
Happy的楠姐 2020-12-11 04:47

I\'m writing a powershell program to replace strings using

-replace \"$in\", \"$out\"

It doesn\'t work for strings containing a backslash,

2条回答
  •  有刺的猬
    2020-12-11 05:05

    You'll need to either escape the backslash in the pattern with another backslash or use the .Replace() method instead of the -replace operator (but be advised they may perform differently):

    PS C:\> 'asdf' -replace 'as', 'b'
    bdf
    PS C:\> 'a\sdf' -replace 'a\s', 'b'
    a\sdf
    PS C:\> 'a\sdf' -replace 'a\\s', 'b'
    bdf
    PS C:\> 'a\sdf' -replace ('a\s' -replace '\\','\\'), 'b'
    bdf
    

    Note that only the search pattern string needs to be escaped. The code -replace '\\','\\' says, "replace the escaped pattern string '\\', which is a single backslash, with the unescaped literal string '\\' which is two backslashes."

    So, you should be able to use:

    -replace ("$in" -replace '\\','\\'), "$out"
    

    [Note: briantist's solution is better.]

    However, if your pattern has consecutive backslashes, you'll need to test it.

    Or, you can use the .Replace() string method, but as I said above, it may not perfectly match the behavior of the -replace operator:

    PS C:\> 'a\sdf'.replace('a\\s', 'b')
    a\sdf
    PS C:\> 'a\sdf'.replace( 'a\s', 'b')
    bdf
    

提交回复
热议问题