Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Perl regex doesn't match "\n" with a following character?

Tags:

regex

perl

This is my file foo.txt:

a
b

This is what I'm doing:

$ perl -pi -e 's/\nb/z/g' foo.txt

Nothing changes in the file, while I'm expecting it to become:

az

Why? It's Perl v5.34.0.

like image 249
yegor256 Avatar asked Nov 18 '25 16:11

yegor256


1 Answers

The firs time you evaluate the substitution, you match against a␊. The second time, against b␊. So it doesn't match either times.

You want to match against the entire file. You can tell Perl to consider the entire file one line by using -g aka -0777.

perl -i -gpe's/\nb/z/g' foo.txt    # 5.36+
perl -i -0777pe's/\nb/z/g' foo.txt
like image 174
ikegami Avatar answered Nov 21 '25 05:11

ikegami