使用 Perl 特殊字符替换 Perl 中的变量

Variable substitution in Perl with Perl special characters

我想用 Perl 替换包含 @ 字符的子字符串,如下面的 sed 命令:

substitution='newusername@anotherwebsite.com'
sed 's/oldusername@website.com/'"${substitution}"'/g' <<< "The current e-mail address is oldusername@website.com"

目前,无论我使用 Perl 而不是 sed 或 awk,我都会先将 \ 替换为 \,将 / 替换为 \/,将 $ 替换为 $@\@;例如

substitution='newusername@anotherwebsite.com'
substitution="${substitution//\/\\}"
substitution="${substitution//\//\/}"
substitution="${substitution//$/\$}"
substitution="${substitution//@/\@}"
perl -pe 's/oldusername\@website.com/'"${substitution}"'/g' <<< "The current e-mail address is oldusername@website.com"

我读过有关使用单引号的内容(如下所示基于 ),但我想知道是否还有其他方法可以使用正斜杠来做到这一点?

substitution='newusername@anotherwebsite.com'
perl -pe "s'oldusername@website.com'"${substitution}"'g" <<< "The current e-mail address is oldusername@website.com"

此外,除了$@%之外,Perl中是否还有特殊字符(为什么不需要转义%)?

最干净的方法是将值传递给 Perl,因为它可以正确处理替换模式和替换中的变量。使用单引号,这样 shell 的变量扩展就不会受到干扰。您可以使用 -s 选项(在 perlrun 中解释)。

#!/bin/bash
pattern=oldusername@website.com
substitution=newusername@anotherwebsite.com
perl -spe 's/\Q$pat/$sub/g' -- -pat="$pattern" -sub="$substitution" <<< "The current e-mail address is oldusername@website.com"

或通过环境将值传播到 Perl。

pattern=oldusername@website.com
substitution=newusername@anotherwebsite.com
pat=$pattern sub=$substitution perl -pe 's/\Q$ENV{pat}/$ENV{sub}/g' <<< "The current e-mail address is oldusername@website.com"

请注意,您需要在调用 Perl 之前分配值,或者您需要 export 它们以便将它们传播到环境中。

\Qquotemeta 应用于模式,即转义所有特殊字符,以便按字面解释。

不需要反斜杠 %,因为哈希值不会插入双引号或正则表达式中。