Reputation: 259
I cannot wrap my head around this...
Why does this construct not work:
printf -v REGEX "%s\\|" "string1" "string2"
REPLACE="blabla"
sed "s/${REGEX}/${REPLACE}/" file1 > file2
But this works:
REGEX="string1\|string2\|"
REPLACE="blabla"
sed "s/${REGEX}/${REPLACE}/" file1 > file2
printf
creates the same string as the one in the second example, yet sed cannot substitute it. Instead, it places the REPLACE
string at the beginning of every line in file2
.
Upvotes: 0
Views: 2564
Reputation: 295687
Consider instead:
printf -v regex '%s|' string1 string2
sed -r -e "s/${regex%|}/$replace/" file1 > file2
This works because it removes the trailing |
from the regex, preventing it from matching the empty string.
Upvotes: 2