我想用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"我读过关于使用单引号(如下面基于sed/ perl with special characters (@)的)的文章,但我想知道是否有其他方法可以使用正斜杠?
substitution='newusername@anotherwebsite.com'
perl -pe "s'oldusername@website.com'"${substitution}"'g" <<< "The current e-mail address is oldusername@website.com"此外,除了$、@和%之外,Perl中是否还有特殊字符(为什么不需要对%进行转义)?
发布于 2021-04-16 15:50:58
最干净的方法是将值传递给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应用于模式,即它转义所有特殊字符,以便按字面解释它们。
没有必要对%进行反斜杠,因为散列不会插入到双引号或正则表达式中。
https://stackoverflow.com/questions/67120916
复制相似问题