shell 中棘手的支撑扩展
使用 POSIX shell 时,以下
touch {quick,man,strong}ly
内容扩展为
touch quickly manly strongly
Which will touch the files quickly
、manly
和 strongly
,但是是否可以动态创建扩张? 例如,以下说明了我想要执行的操作,但由于扩展顺序而不起作用:
TEST=quick,man,strong #possibly output from a program
echo {$TEST}ly
有什么方法可以实现此目的吗? 如果需要的话,我不介意将自己限制在 Bash 上。 我还想避免循环。 扩展应该作为任意程序的完整参数给出(即该程序不能为每个文件调用一次,只能为所有文件调用一次)。 我了解 xargs,但我希望这一切都可以以某种方式从 shell 完成。
When using a POSIX shell, the following
touch {quick,man,strong}ly
expands to
touch quickly manly strongly
Which will touch the files quickly
, manly
, and strongly
, but is it possible to dynamically create the expansion? For example, the following illustrates what I want to do, but does not work because of the order of expansion:
TEST=quick,man,strong #possibly output from a program
echo {$TEST}ly
Is there any way to achieve this? I do not mind constricting myself to Bash if need be. I would also like to avoid loops. The expansion should be given as complete arguments to any arbitrary program (i.e. the program cannot be called once for each file, it can only be called once for all files). I know about xargs
but I'm hoping it can all be done from the shell somehow.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
...使用
eval
有很多错误。 您所要求的只能通过eval
实现,但是您可能想要的东西很容易实现,而无需诉诸bash bug-central。使用数组! 每当您需要将多个项保存在一个数据类型中时,您就需要(或者应该使用)一个数组。
这正是您想要的,没有此处其他建议中引入和隐藏的数千个错误和安全问题。
它的工作方式是:
"${foo[@]}"
:通过扩展名为foo
的数组,并正确引用它的每个元素来扩展该数组。 不要忘记引号!${foo/a/b}
:这是一种参数扩展,它将foo
扩展中的第一个a
替换为 <代码>b。 在这种类型的扩展中,您可以使用%
来表示扩展值的结尾,有点像正则表达式中的$
。foo
的每个元素,将其正确引用为单独的参数,并将每个元素的结尾替换为ly
。... There is so much wrong with using
eval
. What you're asking is only possible witheval
, BUT what you might want is easily possible without having to resort to bash bug-central.Use arrays! Whenever you need to keep multiple items in one datatype, you need (or, should use) an array.
That does exactly what you want without the thousand bugs and security issues introduced and concealed in the other suggestions here.
The way it works is:
"${foo[@]}"
: Expands the array namedfoo
by expanding each of its elements, properly quoted. Don't forget the quotes!${foo/a/b}
: This is a type of parameter expansion that replaces the firsta
infoo
's expansion by ab
. In this type of expansion you can use%
to signify the end of the expanded value, sort of like$
in regular expressions.foo
, properly quote it as a separate argument, and replace each element's end byly
.在 bash 中,您可以执行以下操作:
最后一行被注释掉,但会触及指定的文件。
In bash, you can do this:
That last line is commented out but will touch the specified files.
Zsh 可以轻松做到这一点:
变量内容以逗号分隔,然后每个元素分布到大括号周围的字符串中:
Zsh can easily do that:
Variable content is splitted at commas, then each element is distributed to the string around the braces:
从上面的答案中汲取灵感:
Taking inspiration from the answers above: