$ and Perl's global regular expression modifier

前端 未结 3 1129
南旧
南旧 2021-01-02 21:42

I finally figured out how to append text to the end of each line in a file:

perl -pe \'s/$/addthis/\' myfile.txt

However, as I\'m trying to

3条回答
  •  梦毁少年i
    2021-01-02 22:13

    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).

    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.

    With the /g modifier, you're getting all the places that $ would match -- so

    s/$/X/g;
    

    would take a line like "foo\n" and turn it into "fooX\nX".

    Sidebar: The /m modifier will allow $ to match newlines that occur before the end of the string, so that

    s/$/X/mg;
    

    would convert "foo\nbar\n" into "fooX\nbarX\nX".

提交回复
热议问题