bash - 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
它们才能将它们传播到环境中。
将quotemeta\Q
应用于模式,即它转义所有特殊字符,以便按字面意思解释它们。
不需要反斜杠%
,因为哈希不会插入双引号或正则表达式中。
推荐阅读
- python - AttributeError:模块 'cv2' 没有属性 'VideoCapture'
- django - /account/reset_password/ 处的 OSError 以及 /student/register/ 处的 OSError [Errno 99] 无法分配请求的地址
- fastlane - 找不到通道“ios 调试”。可用通道:ios beta
- c++ - 将 wchar_t 转换为 wstring
- python - np.where 用于包含特定单词的字符串
- f# - F# 在 func `lambda` 和 `lambda` 之间存在差异 |> func
- windows - makefile:如何在 WSL 中运行单个命令
- javascript - 将纯 JavaScript 对象转换为类的实例
- java - 从 ConcurrentLinkedQueue 中迭代和删除元素
- lambda - 如何传递适用于 prism ObservesProperty 的表达式