整蛊括号扩展壳 [英] Tricky brace expansion in shell

查看:216
本文介绍了整蛊括号扩展壳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用POSIX外壳,以下

When using a POSIX shell, the following

touch {quick,man,strong}ly

扩展到

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

有什么办法来实现这一目标?我不介意自己收缩来砸如果需要的话。我也想避免环路。膨胀应为完成参数为任意节目(即,节目不能调用一次为每个文件,它只能使用一次的所有文件调用)。我知道的xargs 但我希望它都可以从某种程度上壳完成的。

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.

推荐答案

...有使用如此多的错误评估。什么你问是唯一可能与评估 BUT 你可能会希望是容易做到,而不必诉诸bash的bug的中央。

... There is so much wrong with using eval. What you're asking is only possible with eval, 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.

TEST=(quick man strong)
touch "${TEST[@]/%/ly}"

这不正是你想要的东西没有千错误,介绍和隐藏在这里的其他建议的安全问题。

That does exactly what you want without the thousand bugs and security issues introduced and concealed in the other suggestions here.

它的工作方式是:


  • $ {foo的[@]}:扩展名为数组通过扩大它的每个元素,正确引用。不要忘了引号!

  • $ {富/ A / B} :这是一个类型参数的扩张,取代了第一个 A 的一个扩张b 。在这种类型的扩展,你可以使用来表示的扩展后的值的末尾的,有点像 $ 常规EX pressions。

  • 把所有的一起,$ {foo的[@] /%/ LY}将扩大,正确地引用它作为一个单独的参数中的每个元素,通过替换每个元素的结束LY

  • "${foo[@]}": Expands the array named foo 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 first a in foo's expansion by a b. In this type of expansion you can use % to signify the end of the expanded value, sort of like $ in regular expressions.
  • Put all that together and "${foo[@]/%/ly}" will expand each element of foo, properly quote it as a separate argument, and replace each element's end by ly.

这篇关于整蛊括号扩展壳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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