How to replace a block of text in multiple files

Suppose you need to replace a single block of text within a file with a different block of text. While you could probably use a text editor such as notepad or notepad++ to accomplish this, what if you needed to replace that same block of text in multiple files? I don’t want to have to open each file in a text editor and do the same search and replace operation over and over again.

At first, I thought I could do this with awk or sed but those are line-based tools and I found that I had to jump through a lot of hoops to get them to work on multi-line blocks. So I wrote this quick perl script. Just edit the script and put the text you want to replace in the $search variable, then put the text you want to replace it with in the $replace variable.

Then run the script like this:

$ ./block-replace.pl file_to_modify.html

You can target multiple files using shell expansion

$ ./block-replace.pl *.html *.twig

You can download block-replace.pl from my GitHib repository

Add a Comment

Your email address will not be published.