[英]escaping single quote sign in PowerShell
I have a replace statement in my code whereby Band's is being replaced by Cig's. 我的代码中有一个替换语句,Band正在被Cig取代。 However when I put single quote it took the first sentence... Example 'Band'
然而,当我把单引号时,它采取了第一句话......示例'乐队'
I tried to use double quote but it does not work. 我试图使用双引号,但它不起作用。 Do you know how to escape the single quote sign?
你知道怎么逃避单引号吗?
-replace 'Band's', 'Cig's'
See Escape characters, Delimiters and Quotes and Get-Help about_Quoting_Rules
from the built-in help (as pointed out by as Nacimota). 请参阅内置
Get-Help about_Quoting_Rules
Escape characters,Delimiters和Quotes以及Get-Help about_Quoting_Rules
(如Nacimota所指出)。
To include a '
inside a single-quoted string, simply double it up as ''
. 要在单引号字符串中加入
'
,只需将其加倍为''
。 (Single-quote literals don't support any of the other escape characters.) (单引号文字不支持任何其他转义字符。)
> "Band's Toothpaste" -replace 'Band''s', 'Cig''s'
Or, simply switch to double-quotes. 或者,只需切换到双引号即可。 (Double-quote literals are required when wishing to use interpolation or escape characters.)
(当希望使用插值或转义字符时,需要双引号文字。)
> "Band's Toothpaste" -replace "Band's", "Cig's"
(Don't forget that -replace
uses a regular expression ) (不要忘记
-replace
使用正则表达式 )
Escape a single quote with two single quotes: 用两个单引号来逃避单引号:
"Band's Toothpaste" -replace 'Band''s', 'Cig''s'
Also, this is a duplicate of Can I use a single quote in a Powershell 'string'? 此外,这是一个副本我可以在Powershell'字符串'中使用单引号吗?
For trivial cases, you can use embedded escape characters. 对于普通的情况,您可以使用嵌入的转义字符。 For more complex cases, you can use here-strings.
对于更复杂的情况,您可以使用here-strings。
$Find = [regex]::escape(@'
Band's
'@)
$Replace = @'
Cig's
'@
"Band's Toothpaste" -replace $Find,$Replace
Then put the literal text you want to search for and replace in the here-strings. 然后将要搜索的文字文本放在here-strings中。
Normal quoting rules don't apply within the here-string @' - '@ delimiters, so you can put whatever kind of quotes you want, wherever you want them without needing any escape characters. 正常引用规则不适用于here-string @' - '@ delimiters,因此您可以在任何地方放置所需的引号,无需任何转义字符。
The [regex]::excape() on $Find will take care of doing the backslash escapes on any regex reserved characters that might be in the search pattern. $ Find上的[regex] :: excape()将处理可能在搜索模式中的任何正则表达式保留字符的反斜杠转义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.