问题描述
我终于想出了如何将文本附加到文件中每一行的末尾:
I finally figured out how to append text to the end of each line in a file:
perl -pe 's/$/addthis/' myfile.txt
但是,当我尝试学习 Perl 以经常使用正则表达式时,我无法弄清楚为什么以下 perl 命令将文本addthis"添加到末尾并开始每行:
However, as I'm trying to learn Perl for frequent regex use, I can't figure out why is it that the following perl command adds the text 'addthis' to the end and start of each line:
perl -pe 's/$/addthis/g' myfile.txt
我认为无论正则表达式匹配使用什么修饰符,$"都会匹配行尾,但我猜这是错误的?
I thought that '$' matched the end of a line no matter what modifier was used for the regex match, but I guess this is wrong?
推荐答案
总结:对于你正在做的事情,删除 /g
以便它只匹配 before 换行符./g
告诉它在换行符之前匹配 和 字符串末尾(在换行符之后).
Summary: For what you're doing, drop the /g
so it only matches before the newline. The /g
is telling it to match before the newline and at the end of the string (after the newline).
如果没有 /m
修饰符,$
将匹配换行符之前(如果它出现在字符串的末尾)或字符串的末尾.例如,对于 "foo"
和 "foo\n"
,$
将在 foo
之后匹配.但是,对于 "foo\nbar"
,它会在 bar
之后匹配,因为 embedded 换行符不在字符串的末尾.
Without the /m
modifier, $
will match either before a newline (if it occurs at the end of the string) or at the end of the string. For instance, with both "foo"
and "foo\n"
, the $
would match after foo
. With "foo\nbar"
, though, it would match after bar
, because the embedded newline isn't at the end of the string.
使用 /g
修饰符,您将获得 $
匹配的所有位置 -- 所以
With the /g
modifier, you're getting all the places that $
would match -- so
s/$/X/g;
将像 "foo\n"
这样的一行变成 "fooX\nX"
.
would take a line like "foo\n"
and turn it into "fooX\nX"
.
侧边栏:/m
修饰符将允许 $
匹配出现在字符串末尾之前的换行符,以便
Sidebar:The /m
modifier will allow $
to match newlines that occur before the end of the string, so that
s/$/X/mg;
会将 "foo\nbar\n"
转换为 "fooX\nbarX\nX"
.
这篇关于$ 和 Perl 的全局正则表达式修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!