英文:
Bash - multiple nested quotes
问题
如何解决这种多层嵌套引号?
这是一个命令的示例:
awk 'BEGIN{system("bash -c \" echo cat /etc/passwd|grep ?root? \" ")}'
我尝试过使用 \',但不起作用:
awk 'BEGIN{system("bash -c \" echo cat /etc/passwd|grep \'root\' \" ")}'
英文:
How can i solve that kind of multiple nested quotes?
this is an example of the command:
awk 'BEGIN{system("bash -c \" echo cat /etc/passwd|grep ?root? \" ")}'
I tried with \' but it does not work..:
awk 'BEGIN{system("bash -c \" echo cat /etc/passwd|grep \'root\' \" ")}'
答案1
得分: 1
你不能在shell中的'
-分隔字符串中包含'
,即使尝试转义也不行。有多种方法,但对于命令行工具脚本或存储在文件中的工具脚本而言,可行的方法是在需要'
时使用\047
。
awk 'BEGIN{system("bash -c \" echo cat /etc/passwd|grep \047root\047 \"")}'
请参阅http://awk.freeshell.org/PrintASingleQuote。
不清楚为什么要写cat /etc/passwd|grep 'root'
而不是grep 'root' /etc/passwd
,以及echo
的用途是什么,但我假设您只是在这里用它来测试引号。
英文:
You cannot include a '
in a '
-delimited string in shell, including in scripts, even when you try to escape it. There are options but the one that works for command-line tool scripts or tool scripts stored in files is to use \047
wherever you need a '
.
awk 'BEGIN{system("bash -c \" echo cat /etc/passwd|grep 7root7 \" ")}'
See http://awk.freeshell.org/PrintASingleQuote.
It's not clear why you'd write cat /etc/passwd|grep 'root'
instead of grep 'root' /etc/passwd
or what the echo
is for but I assume you're just using it here to test quotes.
答案2
得分: 1
以下是您要翻译的内容:
嵌套引号和双引号的三种不同方式
第一种 常见 方法:转义双引号:
awk "BEGIN{system(\"bash -c 'cat /etc/passwd|grep \\\"root\\\" ' \" )}"
在准备 awk
的命令行时,必须考虑 [tag:bash] 转义双引号,然后指示 awk
转义双引号... 但这可能很快变得令人困惑!
第二种方法使用 变量 和 内联脚本:
read -r awkScript <<eoScript
BEGIN{system("bash -c 'cat /etc/passwd|grep \"root\" ' " )}
eoScript
然后
awk "$awkScript"
我觉得这更加 可读!
第三种方式,使用字符的 八进制 值:
使用 $'
和单引号来包装字符串,每个 单引号 必须替换为八进制值:\047
(或\47
),并且必须转义 反斜杠 (\\
)。
awk $'BEGIN{system("bash -c cat /etc/passwd|grep \\\"root\\\" " )}'
通过使用八进制值,您可以表示几乎您想要的任何内容!
英文:
Nesting quote and double quotes 3 different ways
First common way: escaping double quotes:
awk "BEGIN{system(\"bash -c 'cat /etc/passwd|grep \\\"root\\\" ' \" )}"
You have to consider [tag:bash] preparing command line for awk
. Escape double quotes, then instruct awk to escape double quotes... But this could become quickly confusing!
Second way using variable AND Inline script:
read -r awkScript <<eoScript
BEGIN{system("bash -c 'cat /etc/passwd|grep \"root\" ' " )}
eoScript
Then
awk "$awkScript"
I find this more readable!
Third way, using octal values of characters:
Using $'
and single quotes for enclosing string, every single-quotes have to be replaced by octal value: \047
(or \47
), and backslashes have to be escaped too (\\
).
awk $'BEGIN{system("bash -c cat /etc/passwd|grep \\"root\\" " )}'
By using octal values, you could represent near everything you want!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论