如何转义正则表达式中使用的 Perl 文本中的斜杠?
end_date=$(date +"%m/%d/%Y")
/usr/bin/perl -pi -e "s/_end_date_/${end_date}/g" filename
我想用当前日期替换字符串“_end_date_”。由于当前日期中有斜杠(是的,我想要斜杠),所以我需要转义它们。我该怎么做?
我尝试了几种方法,例如使用 sed 和 Perl 本身将斜杠替换为“/”,但没有成功。最后我使用“cut”将日期分成三部分并转义斜杠,但这个解决方案看起来不太好。有更好的解决方案吗?
end_date=$(date +"%m/%d/%Y")
/usr/bin/perl -pi -e "s/_end_date_/${end_date}/g" filename
I want to replace string '_end_date_' with the current date. Since the current date has slashes in it (yes, I want the slashes), I need to escape them. How can I do this?
I've tried several ways, like replacing slashes with "/" using sed and Perl itself, but it didn't work. Finally I used 'cut' to break date in 3 parts and escaped slashes, but this solution doesn't look good. Is there a better solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Perl 中,您可以选择使用哪个字符来分隔正则表达式的各个部分。下面的代码可以正常工作。
这是为了避免“牙签倾斜”综合症与 / 交替出现。
In Perl you can choose which character to use to separate parts of a regular expression. The following code will work fine.
This is to avoid the 'leaning toothpick' syndrome with / alternating.
使用不同的
s
分隔符:s{all/the/slashes/you/want/}{replacement}
。Use a different
s
delimiter:s{all/the/slashes/you/want/}{replacement}
.我建议更改分隔符,但您几乎总是可以使用 quotemeta:
但您也有这条路线:
它与您的两条线执行相同的操作。
I would recommend changing the delimiter, but you can almost always get by with quotemeta:
But you also have this route:
which does the same thing as your two lines.
基于 Axeman 的答案,以下内容对我有用:
需要注意的一些事项
$ed
/ >。'
而不是"
,否则您最终必须引用$
-MPOSIX=strftime< /code> 到
BEGIN { 使用 POSIX qw}
Building on Axeman's answer, the following works for me :
A few things to note
/
in the variable$ed
.'
rather than"
as otherwise you end up having to quote$
-MPOSIX=strftime
toBEGIN { use POSIX qw<strftime> }