问题描述
是否可以按照以下方式做一些事情?
Is it possible to do something along the lines of:
echo ${$(ls)/foo/bar}
我很确定我在某个地方看到了类似的例子,但这会导致替换错误".
I'm pretty sure i saw somewhere working example of something like that but this results in "bad substitution" error.
我知道还有其他方法可以做到这一点,但如此短的oneliner会很有用.我错过了什么吗?还是不可能?
I know that there are other methods to do that but such a short oneliner would be useful. Am I missing something or is this impossible?
推荐答案
语法${...}
仅允许引用变量(或位置参数)(可选)结合参数扩展 .
Syntax ${...}
only allows referencing a variable (or positional parameter), optionally combined with parameter expansion.
语法$(...)
(或更可取的是,其旧式等效项`...`
)执行 命令替换 ,它允许将任意命令嵌入到其 stdout输出表达式 expands strong>.
Syntax $(...)
(or, less preferably, its old-style equivalent, `...`
), performs command substitution, which allows embedding arbitrary commands to whose stdout output the expression expands.
因此,您可以结合这两个功能,如下所示:
Thus, you could combine the two features as follows:
echo "$(lsOutput=$(ls); echo "${lsOutput//foo/bar}")"
也就是说,您在命令替换中定义的任何变量都限于该命令仍在运行的 subshell 中,因此您可以只使用生成所需 output ,因为只有stdout输出才重要.
That said, any variables you define inside the command substitution are confined to the subshell that the command runs in anyway, so you could make do with just a command that produces the desired output, given that it is only the stdout output that matters.
echo "$(ls | sed 's/foo/bar/')"
这篇关于用字符串替换命令替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!