geotheory
geotheory

Reputation: 23660

"Substitution replacement not terminated" with variable

Found this error in other questions, but I can't see how the solutions relate to this.

Assume a file test containing:

one
twoX
three

I can correct twoX with:

perl -0777 -i -pe 's/twoX/two/igm' test

I can make a function to do this:

replace_str(){ perl -0777 -i -pe 's/'$2'/'$3'/igm' $1; }
replace_str test twoX two

But this fails when the replacement contains a space (possibly other chars):

replace_str test two 'two frogs'
Substitution replacement not terminated at -e line 1.

The perl line works with the space. Why not when called in a function? I've tried with other quotes and e.g. $(echo two frogs) (with and without quotes).

Upvotes: 1

Views: 5497

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

It's because you end the string you pass as argument to Perl for your variable expansions. That makes the regex become two arguments.

Instead just put the whole regex, including variables, inside double-quotes and the shell should expand the variables properly.

So use "s/$2/$3/igm" instead.

Upvotes: 3

Related Questions