用字符串替换命令替换 [英] Command substitution with string substitution

查看:92
本文介绍了用字符串替换命令替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以按照以下方式做一些事情?

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.

语法$(...) (或更可取的是,其旧式等效项`...`)执行

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}")"

请注意$(...)嵌套使用简单,这是与`...`相比的主要优点之一,`...`的使用需要在此处进行转义.

Note the uncomplicated nested use of $(...), which is one of the main advantages over `...`, whose use would require escaping here.

也就是说,您在命令替换中定义的任何变量都限于该命令仍在运行的 subshel​​l 中,因此您可以只使用生成所需 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/')"

这篇关于用字符串替换命令替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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