One-line search and replace command using Perl

I’ve been using these one-line commands for over a decade. They’re a really easy way to do a search and replace across many files using a Perl regular expression.

This example replaces all instances of the word “old” with the word “new” in “myfile”, saving the old file version as “myfile.bak”:

# perl -i.bak -pe 's/old/new/g;' myfile

This replaces all instances of the word “old” with the word “new” in all of the .html files in the current directory:

# perl -i.bak -pe 's/old/new/g;' *.html

This does the same thing, but also updates all .html files in all subdirectories:

# find . -name '*.html' -exec perl -i.bak -pe 's/old/new/g;' {} \;

Hope you find this useful.

2 thoughts on “One-line search and replace command using Perl

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.