首页 > 解决方案 > 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 中除了 , 之外还有特殊字符$@为什么%不需要转义%)?

标签: bashperlsed

解决方案


最简洁的方法是将值传递给 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它们才能将它们传播到环境中。

quotemeta\Q应用于模式,即它转义所有特殊字符,以便按字面意思解释它们。

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


推荐阅读