Using ex to bulk-edit files

I previously wrote about command line scripting with ed and ex. I just had an opportunity to put ex into use in practice.

I needed to edit hundreds of files, searching for a line of text and then deleting it along with the next 22 lines.

I created an exscript file containing this code:

g/block_2/ .,+22 d
x

Update: you can probably simplify that deletion command to this:

g/block_2/d23

Then ran it on a file to test it:

$ ex - index.html < exscript

Once I confirmed that it worked correctly, I ran it on the entire directory:

for f in *.html
do
    ex - $f < exscript
done

This solution worked perfectly for my task, which was to remove a block of text from every page of a website downloaded with wget.

Comments

Let us know your comments by tweeting to @codeselfstudy or emailing [email protected].
(The commenting system here is offline for the moment but will return soon. This blog is still under construction.)

Return to the Code Self Study Blog.