Helping Geeks Win the War on Technology Since 2010

Recursively Search and Replace Strings in Linux with Perl

February 8, 2011

Previously, I covered a dead simple one-line Perl command to perform a string search and replace over multiple files on the Linux command prompt. While it did its job for me that day, today I had to do the same thing but this time recursively over all subdirectories.

For review, the Perl command to do a search and replace on a string is this:

perl -pi -e 's/search/replace/g;' *.txt

To get this to work over multiple files, we are going to rely on the grep command to perform a search for the string to replace and pipe back each file that contains the string in lieu of *.txt in the command above.

This is how it’s done:

perl -pi -e 's/search/replace/g;' `grep -ril search *`

The “search” string is the text you wish to replace and the “replace” string is what you want to replace the old text with.

posted in Linux by helpgeek

Follow comments via the RSS Feed | Leave a comment | Trackback URL

1 Comment to "Recursively Search and Replace Strings in Linux with Perl"

  1. How to Borrow WordPress’s URL Sanitize Function | Geek Help Guide wrote:

    [...] into “how-to-borrow-wordpresss-url-sanitize-function.” After a big of digging (namely a grep for “sanitize”), I narrowed it down to the right function and helper functions in the [...]

Leave Your Comment

 
Powered by Wordpress and MySQL on MDDHosting. Theme by Shlomi Noach, openark.org