bash 如何匹配sed中的单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/91110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to match a single quote in sed
提问by grigy
How to match a single quote in sed if the expression is enclosed in single quotes:
如果表达式包含在单引号中,如何在 sed 中匹配单引号:
sed -e '...'
For example need to match this text:
例如需要匹配此文本:
'foo'
回答by tzot
You can either use:
您可以使用:
"texta'textb" (APOSTROPHE inside QUOTATION MARKs)
or
或者
'texta'\''textb' (APOSTROPHE text APOSTROPHE, then REVERSE SOLIDUS, APOSTROPHE, then APOSTROPHE more text APOSTROPHE)
I used unicode character names. REVERSE SOLIDUS is more commonly known as backslash.
我使用了 unicode 字符名称。REVERSE SOLIDUS 通常称为反斜杠。
In the latter case, you close your apostrophe, then shell-quote your apostrophe with a backslash, then open another apostrophe for the rest of the text.
在后一种情况下,您关闭您的撇号,然后用反斜杠引用您的撇号,然后为文本的其余部分打开另一个撇号。
回答by TimB
As noted in the comments to the question, it's not really about sed, but how to include a quote in a quoted string in a shell (e.g. bash).
正如对该问题的评论所指出的,它并不是真正关于 sed,而是如何在 shell(例如 bash)的带引号的字符串中包含引号。
To clarify a previous answer, you need to escape the quote with a backslash, but you can't do that within a single-quoted expression. From the bash man page:
为了澄清先前的答案,您需要使用反斜杠对引号进行转义,但您不能在单引号表达式中执行此操作。从 bash 手册页:
Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.
将字符括在单引号中会保留引号内每个字符的字面值。单引号之间不能出现单引号,即使前面有反斜杠。
Therefore, you need to terminate the quoted expression, insert the escaped quote, and start a new quoted expression. The shell's quote removal does not add any extra spaces, so in effect you get string concatenation.
因此,您需要终止带引号的表达式,插入转义的引号,然后开始新的带引号的表达式。shell 的引号删除不会添加任何额外的空格,因此实际上您会得到字符串连接。
So, to answer the original question of how to single quote the expression 'foo', you would do something like this:
因此,要回答有关如何单引号表达式 'foo' 的原始问题,您将执行以下操作:
sed -e '...'\''foo'\''...'
(where '...' is the rest of the sed expression).
(其中 '...' 是 sed 表达式的其余部分)。
Overall, for the sake of readability, you'd be much better off changing the surrounding quotes to double quotes if at all possible:
总的来说,为了可读性,如果可能的话,最好将周围的引号更改为双引号:
sed -e "...'foo'..."
[As an example of the potential maintenance nightmare of the first (single quote) approach, note how StackOverflow's syntax highlighting colours the quotes, backslashes and other text -- it's definitely not correct.]
[作为第一种(单引号)方法的潜在维护噩梦的示例,请注意 StackOverflow 的语法如何突出显示引号、反斜杠和其他文本的颜色——这绝对是不正确的。]