Linux – How to do multiline search and replace text (delete) recursively

linuxreplacesearchtext processing

I want to go recursively through a directory and search for specific content in all files. The content should then be replaced if found. With a single line I would make something like this:

find . -type f -exec sed -i -e 's@code2replace@@g' {} \;

It sometimes worked and sometimes not (not sufficient hard drive space …). Now I would need something for a multine replacement. The orignal file should be overwritten and the multiline pattern could be rather long. So perhaps storing in an external file would be easier I think.

The code which should be replaced looks like the following:

#c3284d#
echo(gzinflate(base64_decode("sylOLsos....")));
#/c3284d#

Also which characters do I have to escape?

Best Answer

Sed can do a lot of things beside simple search-and-replace, and that includes multiline support.

Here's a blog post on how someone did this (he wrote a sedml script for "sed multiline": http://austinmatzko.com/2008/04/26/sed-multi-line-search-and-replace/

The basic idea is to copy the whole file to sed's "hold buffer", run the regex on that and then write out the changed file. However, this approach may be rather slow if your files are large as you're loading a whole file at a time into memory.

Related Question