简体   繁体   中英

How to replace regex multiline dotall using perl in command line

Hi I am new using perl and I would like to know how to use it to replace regex in multline mode. And if possible to also make the "." match with break lines.

I am using the following expression:

perl -pe 's/text.*end/textChanged/g' myFile.txt

The expression above replace in single line mode. It does not consider break lines.

Using: Windows Stranberry Perl

Note that Perl one-liner uses -p or -n switch which wraps a while loop behind the scenes. And the while loop uses scalar context which reads line by line, so you will not see any changes in your output unless the text.*end appears in a single line.

Here is a sample

$ cat  a.txt
abc
text 1 2
2 3 4
ab end
hello
here

$ perl -pe 's/text.*end/textChanged/g' a.txt # Nothing happens - while reads line by line
abc
text 1 2
2 3 4
ab end
hello
here

Now, you can do like setting the Record separator variable to undef .

$ perl -pe ' BEGIN { $/=undef } s/text.*end/textChanged/g' a.txt # Nothing happens
abc
text 1 2
2 3 4
ab end
hello
here

But, when you add the /s modifier, the substitution takes place.

$ perl -pe ' BEGIN { $/=undef } s/text.*end/textChanged/gs ' a.txt
abc
textChanged
hello
here
$

Reading the entire file using slurp mode and again nothing happens with your substitution.

$ perl -0777 -pe ' s/text.*end/textChanged/g ' a.txt
abc
text 1 2
2 3 4
ab end
hello
here
$

Now you use the /s flag so that dot can match the newline as well and the substitution takes place.

$ perl -0777 -pe ' s/text.*end/textChanged/gs ' a.txt
abc
textChanged
hello
here
$

Thanks @ikegami... for the bundle options, like below

$ perl -0777pe ' s/text.*end/textChanged/gs ' a.txt

So when you want the dot to match newlines, you need to add the /s modifier in the regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM