physicalattraction
physicalattraction

Reputation: 6858

Replace multiline string in all files in terminal

I have a couple of files in a directory, in which I have a piece of text between two separators.

Text to keep

//###==###
Text to remove
//###==###

Text to keep

After an extensive search, I found the following Mac OS X Terminal command, with which I can remove the separators themselves.

perl -pi -w -e 's|//###==###||g' `find . -type f`

However, I need something with a regex that does not only remove the separators themselves, but also what is in between. Something like this, although this line doesn't do anything.

perl -pi -w -e 's|//###==###(.*)//###==###||g' `find . -type f`

EDIT AFTER DUPLICATE FLAG

I see something similar here, using the scalar range operator, but I cannot make it work for me. Failed attempts include:

perl -pi -w -e 's|//###==###..//###==###||g' `find . -type f`
perl -pi -w -e 's|//###==###(..)//###==###||g' `find . -type f`
perl -pi -w -e 's|//###==###[..]//###==###||g' `find . -type f`

SOLUTION

With the help of dawg below, the following oneliner will do exactly what I want:

$ perl -0777 -p -i -e 's/(^\s*^\/\/###==###.*?\/\/###==###\s*)//gms' `find . -type f -name "index.php"`

Upvotes: 2

Views: 895

Answers (1)

dawg
dawg

Reputation: 103884

You can use:

s/(^\s*^\/\/###==###.*?\/\/###==###\s*)//gms

Working Demo

Then in the terminal and in Perl. Given:

$ echo "$tgt"
Text to keep

//###==###
Text to remove
//###==###

Text to keep

Use the -0777 command flag to slurp the whole file and then:

$ echo "$tgt" | perl -0777 -ple 's/(^\s*^\/\/###==###.*?\/\/###==###\s*)//gms'
Text to keep
Text to keep

Or, you can use the range operator. If done this way, you cannot remove the leading and trailing blank lines if that is your intent:

$ echo "$tgt" | perl -lne 'print unless (/\/\/###==###/ ... /\/\/###==###/)'
Text to keep


Text to keep

Upvotes: 2

Related Questions