MaxPowers
MaxPowers

Reputation: 5486

Parameter expansion in substitution modifier

Let x be a parameter initialized as follows:

x=("drink/beer" "drink/whine" "drink/boooze")

Suppose there are also parameters y and z, with y="drink" amd z="buy", respectively. For each word in x, I want to substitute the portion that machtes y with z. Expected output , hence, is

buy/beer buy/whine buy/boooze

I though the following code would do so:

print ${x:s/${y}/${z}}

However, it does not work. The "drink" substrings are not substituted and I could find the reason in the modifier documentation:

The s/l/r/ substitution works as follows [...] When used in a history expansion, which occurs before any other expansions, l and r are treated as literal strings

This means, that in my attempt zsh literally searchs for "${y}", which is of course not to be found. Is there another way the accomplish my goal, without using an explicite loop?

Upvotes: 1

Views: 71

Answers (1)

chepner
chepner

Reputation: 530920

Parameter expansion has its own replacement syntax, separate from the history modification operators.

% print ${x/$y/$z}
buy/beer buy/whine buy/boooze

Upvotes: 2

Related Questions