Perl中的变量替换与Perl特殊字符

我想@用 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,我都会首先替换, /with /, $with$@with @; 例如

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"

我已经阅读了关于使用单引号的内容(如下基于带有特殊字符 (@) 的 sed/perl),但我想知道是否还有其他方法可以使用正斜杠来做到这一点?

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以便将它们传播到环境中。

Q应用quotemeta的模式,即它避开了所有特殊字符,使他们从字面上解释。

没有必要反斜杠,%因为散列没有插入双引号或正则表达式。

  • @TLP: What do you mean by "easier"? You need to `export` them or assign them before calling Perl, and you need to access the hash to get the values.

以上是Perl中的变量替换与Perl特殊字符的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>