On an unrelated note, you may want to add the \Q
and \E
escape sequences around $a
in your regex:
perl -pe "s/\b\Q$a\E\b/$b/g if m/param1 /" test
They escape any characters that are special to regexes. If you intend for $a
to hold a regex you should probably move the word boundary assertions (\b
) into it.
No matter what you choose to do, you will need to be careful with values in $a
and $b
. For instance:
a="/"
b="slash"
perl -pe "s/\b\Q$a\E\b/$b/g if m/param1 /" test
will cause a syntax error. One solution to this is to not use environment variables to replace code. Perl allows you access to the environment through the %ENV
hash:
perl -pe 's/\b\Q$ENV{a}\E\b/$ENV{b}/g if m/param1 /' test
Notice the use of single ticks to avoid treating $ENV
as a shell variable.