为什么这个用于查找字符串中单引号索引的参数扩展有效? [英] Why does this parameter expansion for finding the index of a single quote in a string work?

查看:24
本文介绍了为什么这个用于查找字符串中单引号索引的参数扩展有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 zsh 中的字符串中提取单个引用的单词,但显然要尝试的方法不起作用,例如:

I was messing around trying to extract a single quoted word from a string in zsh, and the obvious things to try didn't work, like these:

${foo[(i)']}
${foo[(i)'']}
${foo[(i)\']}

当我在命令行上尝试第一个时,它提示我使用 braceparam quote> 继续该行,然后我使用另一个单引号,然后再次使用 braceparam>,我跟着另一个右大括号.令我惊讶的是,这实际上给出了正确的索引.全部连接在一起,这是获取字符串中第一个单引号的索引 $foo:

When I tried that first one on the command line, it prompted me to continue the line with braceparam quote>, which I followed with another single quote, then again with braceparam>, which I followed with another closing brace. Much to my surprise, this actually gave the correct index. All joined together, this is what works to get the index of the first single quote in a string $foo:

${foo[(i)']}'}

很高兴我发现了一些有用的东西,但谁能解释一下它为什么有效?

It's nice that I found something that works, but can anyone explain why it works?

编辑添加完整示例:

foo="a 'bar' -l"
echo ${foo[(i)']}'}                        # echoes "3"
echo ${foo[${foo[(i)']}'},${foo[(I)']}'}]} # echoes "'bar'"

推荐答案

如 chepner 指出的那样

Edit as pointed out by chepner:

since (i) takes a pattern, ${foo[(i)[\']]} should and does work as expected.

<小时>

首先,̶这是如何我想你应该做的取代是这样的:̶


F̶i̶r̶s̶t̶ ̶o̶f̶ ̶a̶l̶l̶,̶ ̶t̶h̶i̶s̶ ̶i̶s̶ ̶h̶o̶w̶ ̶I̶ ̶t̶h̶i̶n̶k̶ ̶y̶o̶u̶ ̶s̶h̶o̶u̶l̶d̶ ̶d̶o̶ ̶t̶h̶e̶ ̶s̶u̶b̶s̶t̶i̶t̶u̶t̶i̶o̶n̶ ̶l̶i̶k̶e̶ ̶t̶h̶i̶s̶:̶

echo "${foo[(i)']}"
#or
echo "$foo[(i)']"

<小时>

现在,̶我看来,你发现任一错误,或怪癖̶z̶s̶h̶.̶我不认为这是设计使然,但语法检查器并没有将引号解释为替代,但作为要完成的报价.


N̶o̶w̶,̶ ̶i̶t̶ ̶s̶e̶e̶m̶s̶ ̶t̶o̶ ̶m̶e̶ ̶t̶h̶a̶t̶ ̶y̶o̶u̶ ̶f̶o̶u̶n̶d̶ ̶e̶i̶t̶h̶e̶r̶ ̶a̶ ̶b̶u̶g̶ ̶o̶r̶ ̶a̶ ̶q̶u̶i̶r̶k̶ ̶o̶f̶ ̶z̶s̶h̶.̶ I don't think this is done by design, but the syntax checker is not intepreting the quote as a single character of the substitution, but as a quote to be completed.

奇怪的是,当您添加一个额外的 }' 时,解析器正确地解释了您的替换.

Weirdly enough the parser is interpreting correctly your substitution when you put an extra }'.

虽然它实际上忽略了它.你可以试试:

Although it is actually ignoring it. You can actually try:

echo ${foo[(i)']}HiMomImOnTV'}

令人惊讶的是它也能正常工作.

And surprisingly it works as well.

也许你应该打开一个错误报告,或者询问开发者邮件列表.

Maybe you should open a bug report, or ask the developer mailing list.

如果您将双引号放在替换上,语法检查器就不会报错并且可以正常工作.我认为您应该添加它们,因为您建议的表单(不带双引号)未记录在案,并且行为可能会在 zsh 的未来版本中发生变化.

If you put the double quote over the substitution the syntax checker doesn't complain and it works correctly. I think you should add them, because the form you suggested (without double quotes), is not documented, and the behaviour might change in future versions of zsh.

这篇关于为什么这个用于查找字符串中单引号索引的参数扩展有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆