Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

bash - Command substitution with string substitution

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...