Linux 如何在 Bash 中的单引号字符串中转义单引号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8254120/
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 escape a single quote in single quote string in Bash?
提问by u351545
I want to display a string in Bash like this
我想像这样在 Bash 中显示一个字符串
I'm a student
Of course you can do it like this
当然你可以这样做
echo "I'm a student"
But how to accomplish this while using single quote around the string ?
但是如何在字符串周围使用单引号来实现这一点?
采纳答案by codaddict
echo 'I\'m a student'
does not work. But the following works:
不起作用。但以下工作:
echo $'I\'m a student'
From the man page of bash:
从 bash 的手册页:
A single quote may not occur between single quotes, even when preceded by a backslash.
....
Words of the form $'string'are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.
单引号之间不能出现单引号,即使前面有反斜杠。
.... $'string'
形式的单词被特殊处理。单词扩展为字符串,并按照 ANSI C 标准的规定替换反斜杠转义字符。
回答by Luke Gedeon
The "ugly" solution mentioned by Glenn Hymanman should actually be listed as a top level answer. It works well and is actually beautiful in some situations.
Glenn Hymanman 提到的“丑陋”解决方案实际上应该列为顶级答案。它运作良好,在某些情况下实际上很漂亮。
'I'"'"'m a student'
This ends the single quoted string after I
then immediately starts a double quoted string containing a single quote and then starts another single quoted string. Bash then concatenates all contiguous strings into one.
这将结束单引号字符串,I
然后立即开始包含单引号的双引号字符串,然后开始另一个单引号字符串。Bash 然后将所有连续的字符串连接成一个。
Beautiful!
美丽的!
回答by Nick Jensen
The example below works because the escaped single quote \'
is technically between two single-quoted arguments
下面的示例有效,因为转义的单引号\'
在技术上位于两个单引号参数之间
echo 'I'\''m a student'