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?

+3


source to share


2 answers


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/')"

      

+2


source


You can use pipe |

with sed

for example:

$ echo ABC | sed 's/B/_/'
A_C

      



Or variable substitution, all explained here and especially in the Variable / Substitution Expansion section, and below is an example from me:

$ var=ABC
$ echo ${var//B/_}
A_C

      

+1


source







All Articles