Command Substitution with Line Replacement
Is it possible to do something line by line:
echo ${$(ls)/foo/bar}
I'm pretty sure I've seen a working example of something like this somewhere, but it results in a "bad replacement" error.
I know there are other ways to do this, but such a short oneliner would be helpful. Am I missing something or is it not possible?
source to share
The syntax${...}
allows you to reference a variable (or positional parameter), optionally in conjunction with parameter expansion .
The syntax$(...)
(or, less preferably, its old-style equivalent `...`
), does , allows arbitrary commands to be inlined , whose output stdout expression is expanded .
So you can combine the two functions like this:
echo "$(lsOutput=$(ls); echo "${lsOutput//foo/bar}")"
Note the uncomplicated nested usage $(...)
, which is one of the main advantages over `...`
using which requires escaping here.
However, any variables you define inside command substitution are limited to the subshell that the command runs anyway, so you can only do with a command that produces the output you want , given that only the output of stdout matters.
echo "$(ls | sed 's/foo/bar/')"
source to share