-

 

Shell Search And Replace using find and sed

We wrote this when we were refactoring our cms.

Rather than manually change thousands of calls to ->Get[Something] to->get[Something] and many other variations we used this find and sed hack to achieve the same result in a fraction of the time.

 

Instructions

  1. Add in the OLD and NEW regex expressions you want sed to search for in the found my find. Duplicate the sed lines as you need, this script will handle multiple expressions because of the -e option
  2. Savethe edited mySandRScript.sh in the root of the directories you want to search and replace
  3. Edit the command as follows;
    1. Add in the FILEREGEXFILTER as a filter to find the files you want to process.
    2. If you want to exclude directories then you can duplicate "-path 'PATH/TO/EXCLUDE' -prune -o" bit. The -o means 'or' so links to the next expression.
    3. Then run the command when in that directory, it outputs a file detailing which files where searched.

command

find -path 'PATH/TO/EXCLUDE' -prune -o -type f -regex "FILEREGEXFILTER" -exec ./mySandRScript.sh {} \; > filesSearched.txt

 

mySandRScript.sh

#!/bin/bash

TMP_FILE="/tmp/replace.tmp"
echo $1
cat $1 | sed -e s/OLD/NEW/g \
-e s/OLD2/NEW2/g \
-e s/OLD3/NEW3/g > ${TMP_FILE}
cp ${TMP_FILE} $1
rm ${TMP_FILE}

 

© 2008 Clear Intent All Rights Reserved
powered by clear cms