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 Comments »

  1. Balwinder S Dheeman Said,

    March 4, 2010 @ 2:02 pm

    What’s wrong with using the ’sed’?

    You did not bothered to explain why use perl?

    Have you ever read http://werc.homelinux.net/links/reference_material/unix_prog_design.pdf ?

  2. Earl Ruby Said,

    April 10, 2010 @ 11:46 am

    Nothing. Because I can. Yes.

Leave a Comment