Recursive Find and Replace With grep and Perl

I thought it might be a nice idea to start posting useful little commands and bits of code every now and then–ones I’ve found to be particularly useful. So here’s the first one, recursive find and replace. A masterfully crafted regular expression paired with this command can save you hours of tedious work.


This will search all files recursively for SEARCH_STRING and replace all occurrences of SEARCH_STRING with REPLACE_STRING throughout each unique file found. It also creates a backup of each modified file so that FILE is backed-up as FILE~ (with a tilde).

grep -R --files-with-matches 'SEARCH_STRING' . | sort | uniq | xargs perl -pi~ -e 's/SEARCH_STRING/REPLACE_STRING/'

No related posts.

Comments

4 Responses to “Recursive Find and Replace With grep and Perl”

  1. Christian Hofer on November 19th, 2009 10:20 am

    Thank you very very much :-) )

  2. Russell on June 20th, 2010 11:54 pm

    Cool, worked a treat :)

  3. Jesse on July 13th, 2010 1:36 am

    If you have ack (way faster than grep) you can:
    ack -al test | xargs sed ‘s/test/foo/g’
    to test and add the -i to sed to write the files
    ack -al test | xargs sed -i ‘s/test/foo/g’

    It doesn’t make a backup, but that’s what version control is for, right? ;-)

  4. vinay on February 17th, 2012 3:42 pm

    I am trying to search a variable value inside a file and delete the repeated variable in the file.
    eg:
    variable $v = abc
    file may look like this
    abc.txt

    abc abc 12 12

    NOTE: apart from the variable there may be other chars or numbers repeating. I want only the duplicate variable to be removed.

Leave a Reply